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

问题描述 投票:1回答:2

我想使用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}

引用为空。

javascript reactjs conditional-statements render ref
2个回答
1
投票

类似这样的东西:

// 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
}

0
投票

尝试一下,

render(){
 return(
{this.state.filterActive ? (<label ref={this.firstRef}>Time Range</label>) : (null)}
)}
© www.soinside.com 2019 - 2024. All rights reserved.