簡體   English   中英

React.JS計算虛擬DOM中的img寬度

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

我正在嘗試通過JavaScript找到<img>的寬度來居中。

嘗試計算此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對象(帶有width和height props)公開給你的組件。

您可以像使用它一樣使用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM