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

标签 javascript reactjs conditional-statements render ref

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

相关文章:

javascript - 如何根据 ID 以外的某些属性从集合中查找模型?

javascript - 属性或方法 "users"未定义 vue js 应用程序

javascript - insertBefore javascript,在链接之间添加元素

c# - 传递给函数的条件语句

javascript - 为什么我在以下脚本中得到意外的 "(" token ?

reactjs - 具有替代标签放置的 Material UI Stepper

javascript - 在选择更改事件上 react 提交表单

javascript - 有没有办法在传单 map 上编辑现有的geojson数据

r - 过滤至少具有两个特定值的行

c++ - 我的 windowProc 函数中的奇怪条件语句行为