我试图动态更新元素的样式,但是无论我尝试什么,都发现对该元素的引用是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()
函数。
答案 0 :(得分:1)
您的ref
工作正常!要对其进行测试,只需给div
一种backgroundColor: 'red'
样式和一个调用onClick
的{{1}}属性,您将看到它可以正常工作。
现在,如何实现您的期望是使用{() => this.computeStyle(this.htmlElement, this.props.height)}
而不是componentDidMount
!
onLoad