Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在React中跨层次设置焦点_Reactjs - Fatal编程技术网

Reactjs 如何在React中跨层次设置焦点

Reactjs 如何在React中跨层次设置焦点,reactjs,Reactjs,在我的React聊天应用程序中,我有如下组件的层次结构: ThreadList Thread Reply ReplyMenu ReplyButton <button onClick="?" /> Reply Reply . NewReply <input ref={(in

在我的React聊天应用程序中,我有如下组件的层次结构:

ThreadList
    Thread
        Reply
            ReplyMenu
                ReplyButton
                    <button onClick="?" />

        Reply
        Reply
        .
        NewReply
            <input ref={(input) => {this.replyInput = input}}>
ThreadList
线
回复
答复菜单
答复按钮
回复
回复
.
新答复
{this.replyInput=input}}>
我想要的是,当我按下ReplyButton时,焦点应该设置为NewReply组件内的输入。有人能告诉我如何在React中实现这一点吗。我见过一些例子,其中设置焦点的组件是输入的直接父级,但不在层次结构的不同部分

谢谢,
Frank

您是否尝试对输入调用
focus()

  render(){
  const _this = this;
  <button onClick={() => _this.replyInput.focus()} />
}
render(){
常数this=这个;
_this.replyInput.focus()}/>
}

您必须将click事件传递给父
Reply
组件,然后从那里调用focus函数。因此,您还需要将此函数从
Reply
组件传递给每个子组件,直到
ReplyButton
组件

糟糕的

回复

focusNewReply() {
     this.replyInput.focus();
}
回复菜单

focusNewReply() {
    this.props.focusNewReply();
}
回复按钮

<button onClick={()=>{this.props.focusNewReply()}}>
{this.props.focusNewReply()}}>

是,但由于“this”指的是ReplyButton组件,而不是NewReply组件,因此我收到一个“无法读取未定义的属性'focus'”@FrankJusnes啊,我明白了,在更改渲染组件以保留引用之前,您可以存储
this
NewReply
中的
ref
也是如此。