当我尝试使用条件渲染带有 ref 属性的组件时,react 编译器说它找不到带有附加在 ref 中的函数的组件。
这是容器组件的代码
class Dispersiones extends Component{
constructor(props){
super(props);
this.state = {
showDetailDeposito:false
};
}
onClickRow(row){
this.setState({showDetailDeposito:true});
this.refs.detalle.getDataFromTable(row);
}
render(){
let container={
height:'100%',
width:'100%',
backgroundColor:'cyan',
position:'relative'
};
return(
<div style={container}>
<div style={{width:'100%', height:'50%', backgroundColor:'#3b434d', float:'left'}}>
{
this.state.showDetailDeposito
?
<DetalleDeposito ref="detalle"></DetalleDeposito>
:
null
}
</div>
<div style={{width:'100%', height:'50%', backgroundColor:'white', float:'left',overflow:'auto'}}>
<ListaDepositosPendientes onClickPropTr= {this.onClickRow.bind(this)}></ListaDepositosPendientes>
</div>
</div>
);
};
}
export default Dispersiones;
如您所见,DetalleDeposito 标记具有 ref 属性,但我想在 showDetailDeposito 状态设置为 True 时显示该组件,问题是当我在没有条件的情况下使用该组件时,它会起作用,但只要正如我所说的那样,它失败了。
希望您能告诉我如何根据需要显示的条件来呈现具有 ref 属性的组件。谢谢。
最佳答案
我认为问题是因为您使用的是相同的点击处理程序 onClickRow
都设置 showDetailDeposito
为真,然后使用 ref
调用函数。但是,因为 setState
是异步的,对 ref
的调用失败,因为该组件 <DetalleDeposito />
由于 showDetailDeposito
尚未安装是假的。
要修复,您可以尝试使用 setState
中的回调调用ref
一旦设置了状态就起作用。
this.setState({
showDetailDeposito: true
},
() => this.refs.detalle.getDataFromTable(row)
});
关于javascript - 当有条件地渲染具有 ref 属性的组件时,无法从未定义中读取属性 ...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48757448/