我想使用ref,但是我不能在最初为假的条件渲染中使用它。
constructor(props) {
super(props);
this.state = {
filterActive: false,
}
this.firstRef = React.createRef();
}
如果我在此使用ref:-
{this.state.filterActive ?
<label ref={this.firstRef}>Time Range</label>
:null}
引用为空。
类似这样的东西:
// directly assign the element to this.firstRef
// instead of doing it in the constructor
<label
ref={(elem) => (this.firstRef = elem)}
style={{display: this.state.filterActive ? 'inline-block' : 'none'}}
>
Time Range
</label>
并且在使用this.firstRef时,将您放在一个if这样的内部:
if (this.firstRef) {
// your work
}
尝试一下,
render(){
return(
{this.state.filterActive ? (<label ref={this.firstRef}>Time Range</label>) : (null)}
)}