简体   繁体   English

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

[英]React.JS calculating img width in virtual DOM

I'm trying to find the width of an <img> to center it via JavaScript. 我正在尝试通过JavaScript找到<img>的宽度来居中。

Trying to calculate the width of this react.js DOM node returns 0. 尝试计算此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} />
    );
  }
});

You could use the image's onLoad event to make sure it's loaded before you try this: 在尝试此操作之前,您可以使用图像的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> 

I wrote a React library that exposes a size object (with width and height props) to your components. 我写了一个React库,它将一个size对象(带有width和height props)公开给你的组件。

You can use it like so for your use case: 您可以像使用它一样使用它:

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);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM