React.JS在虚拟DOM中计算img宽度

React.JS calculating img width in virtual DOM

本文关键字:计算 img 宽度 DOM JS 虚拟 React      更新时间:2023-12-07

我正试图找到<img>的宽度,以便通过JavaScript将其居中。

尝试计算此react.js DOM节点的宽度时返回0。

var Player = React.createClass({
  componentDidMount:function(){
      var imgEl = this.refs.imgSize.getDOMNode();
      console.log(imgEl.offsetWidth);
  },
  render: function () {
    return (
      <img ref="imgSize" src={this.props.imageURL} />
    );
  }
});

您可以使用图像的onLoad事件来确保在尝试以下操作之前已加载:

<script src="http://fb.me/react-0.12.2.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
<script type="text/jsx;harmony=true">void function() { "use strict";
var Player = React.createClass({
  _onLoad(e) {
    console.log(e.target.offsetWidth)
  },
  render() {
    return <img src={this.props.imageURL} onLoad={this._onLoad}/>
  }
})
React.render(<Player imageURL="http://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg"/>, document.body)
}()</script>

我写了一个React库,它向组件公开了一个size对象(带有宽度和高度道具)。

你可以在你的用例中这样使用它:

var SizeMe = require('react-sizeme');
var Player = React.createClass({
  componentDidMount:function(){
      var imgEl = this.refs.imgSize.getDOMNode();
      console.log(imgEl.offsetWidth);
  },
  render: function () {
    // height and width via props!!
    var width = this.props.width;
    var height = this.props.height;
    return (
      <img ref="imgSize" src={this.props.imageURL} />
    );
  }
});
// Wrap your component with the SizeMe HOC!
module.exports = SizeMe()(Player);

演示:https://react-sizeme-example-esbefmsitg.now.sh/

Github:https://github.com/ctrlplusb/react-sizeme