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