我正在尝试动态更新元素的样式,但发现对该元素的引用是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>
);
}
}