如何在(条件渲染)中使用 ref

Anu*_*hra 6 javascript render ref conditional-statements reactjs

我想使用 ref,但是我无法在最初为 false 的条件渲染中使用它。

constructor(props) {
    super(props);
    this.state = { 
      filterActive: false,
    }
    this.firstRef = React.createRef();

}
Run Code Online (Sandbox Code Playgroud)

如果我在此使用 ref :-

{this.state.filterActive ?
    <label ref={this.firstRef}>Time Range</label>
:null}
Run Code Online (Sandbox Code Playgroud)

引用为空。

小智 -1

尝试这个,

render(){
 return(
{this.state.filterActive ? (<label ref={this.firstRef}>Time Range</label>) : (null)}
)}
Run Code Online (Sandbox Code Playgroud)