反应-元素引用在onLoad调用中未定义

时间:2019-07-03 20:50:53

标签: reactjs

我试图动态更新元素的样式,但是无论我尝试什么,都发现对该元素的引用是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()函数。

1 个答案:

答案 0 :(得分:1)

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

onLoad