【问题标题】:Use ref to focus but set ref with conditioning使用 ref 聚焦,但设置 ref 条件
【发布时间】:2017-11-21 07:30:24
【问题描述】:
<Editor
    {...other}
    {this.props.isFocus && ref={input => input && input.focus()} }
/>

上面的代码会有错误,如何根据父级传递的标志来聚焦子级组件?

【问题讨论】:

  • 它会抛出什么错误?

标签: javascript reactjs


【解决方案1】:

你不能用这种逻辑来为组件设置一个 prop。您可以改为执行以下操作之一:

<Editor
    {...other}
    ref={this.props.isFocus ? (input => input && input.focus()) : null}
/>

{this.props.isFocus ? <Editor
    {...other}
    ref={input => input && input.focus()}
  />
: <Editor {...other} />}

话虽如此,我认为您没有正确使用ref。我认为没有任何正当理由仅在某些条件下拥有ref;无论您的应用程序逻辑如何,它都应该是静态道具。

否则,您很可能会错误地使用ref,但是如果不查看其余代码,就很难说出原因或方式。

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多