React -Element -element Reference在Onload调用中未定义



我正在尝试动态更新元素的样式,但发现对该元素的引用是undefined,无论我尝试什么。

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

div加载时,我想调用computeStyle功能以更新某些样式。实际功能在其计算中要复杂得多。

但是,在运行此操作时,样式无法正确更新。htmlElement原来是undefined。为什么这是?

注意:我正在使用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>
      );
     }
   }

最新更新