我想使用 ref,但是我无法在最初为 false 的条件渲染中使用它。
constructor(props) {
super(props);
this.state = {
filterActive: false,
}
this.firstRef = React.createRef();
}
如果我在这里使用 ref :-
{this.state.filterActive ?
<label ref={this.firstRef}>Time Range</label>
:null}
ref 为空。
最佳答案
像这样的事情怎么样:
// 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
}
关于javascript - 如何在(条件渲染)中使用 ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58095183/