【发布时间】:2017-11-21 07:30:24
【问题描述】:
<Editor
{...other}
{this.props.isFocus && ref={input => input && input.focus()} }
/>
上面的代码会有错误,如何根据父级传递的标志来聚焦子级组件?
【问题讨论】:
-
它会抛出什么错误?
标签: javascript reactjs
<Editor
{...other}
{this.props.isFocus && ref={input => input && input.focus()} }
/>
上面的代码会有错误,如何根据父级传递的标志来聚焦子级组件?
【问题讨论】:
标签: javascript reactjs
你不能用这种逻辑来为组件设置一个 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,但是如果不查看其余代码,就很难说出原因或方式。
【讨论】: