使用React时查找元素的宽度?

时间:2016-04-07 13:49:04

标签: css reactjs

在React组件生命周期的哪个阶段,我可以获得在css文件中设置的组件css属性吗?

我已经在render方法和componentDidMount方法中尝试过它,并且都没有为组件分配css属性。

export default class HomeArtist extends React.Component {
constructor(props){
    super(props);   
}
componentDidMount(){
    let ImageStore = document.getElementsByClassName('home-artist-display');
    console.log("ComponentDidMount: ", ImageStore);
}
render(){
    var ImageStyle = {
        backgroundImage: "url("+this.props.info.image+")"
    };
    return (
        <div className="home-artist-display" style={ImageStyle}>
            <Link to={"artist/" + this.props.info.id}>
                <h3 className="home-artist-name">{this.props.info.name}</h3>
            </Link>
        </div>
    )
}
}

1 个答案:

答案 0 :(得分:1)

我写了一个React库,它将一个size对象(带有width和height props)暴露给组件。

对于您的用例,您可以这样使用它:

import SizeMe from 'react-sizeme';  // import me!   

class HomeArtist extends React.Component {
  ...
  render(){
      // Size gets passed in as props!
      const { width, height } = this.props.size;

      var ImageStyle = {
          backgroundImage: "url("+this.props.info.image+")"
      };
      return (
          <div className="home-artist-display" style={ImageStyle}>
              <Link to={"artist/" + this.props.info.id}>
                  <h3 className="home-artist-name">{this.props.info.name}</h3>
              </Link>
          </div>
      )
  }
}

// wrap your component export!
export default SizeMe()(HomeArtist);

-

您可以在https://github.com/ctrlplusb/react-sizeme

找到完整的详细信息