Reactjs React-元素引用在onLoad调用中未定义

Reactjs React-元素引用在onLoad调用中未定义,reactjs,Reactjs,我试图动态更新我的元素的样式,但发现对该元素的引用是未定义的 export class MyComponent extends React.Component { computeStyle(htmlElement, height) { if (htmlElement== null) return; htmlElement.style.height = height + "px"; } render() {

我试图动态更新我的元素的样式,但发现对该元素的引用是
未定义的

export class MyComponent extends React.Component {
    computeStyle(htmlElement, height) {
        if (htmlElement== null)
            return;

        htmlElement.style.height = height + "px";
    }

    render() {    
        return (
            <div
                ref={(ref) => this.htmlElement= ref}
                onLoad={() => this.computeStyle(this.htmlElement, this.props.height)}
            >
            </div>
        );
    }
}
导出类MyComponent扩展了React.Component{
computeStyle(htmlElement,高度){
if(htmlElement==null)
回来
htmlElement.style.height=高度+px;
}
render(){
返回(
this.htmlElement=ref}
onLoad={()=>this.computeStyle(this.htmlElement,this.props.height)}
>
);
}
}
加载
div
时,我想调用
computeStyle
函数来更新一些样式。实函数的计算要复杂得多

但是,运行此操作时,样式不会正确更新。
htmlElement
原来是
未定义的
。为什么会这样


注意:我使用的是React 15,无法访问
React.createRef()
函数。

您的
ref
工作正常!要测试它,只需给
div
一个
backgroundColor:'red'
样式,以及一个
onClick
属性,该属性调用
{()=>this.computeStyle(this.htmlElement,this.props.height)}
,您将看到它按预期工作。 现在,如何实现您的期望是使用
componentDidMount
而不是
onLoad

    export class MyComponent extends React.Component {
      componentDidMount() {
        this.computeStyle(this.htmlElement, this.props.height)
      }

    computeStyle(htmlElement, height) {
      if (htmlElement === null) return;

      htmlElement.style.height = height + "px";
    }

    render() {
      return (
        <div
          style={{ backgroundColor: "red" }}
          ref={ref => (this.htmlElement = ref)}
        >
        </div>
      );
     }
   }
导出类MyComponent扩展了React.Component{
componentDidMount(){
this.computeStyle(this.htmlElement、this.props.height)
}
computeStyle(htmlElement,高度){
if(htmlElement==null)返回;
htmlElement.style.height=高度+px;
}
render(){
返回(
(this.htmlElement=ref)}
>
);
}
}