Javascript 使用refs聚焦输入的ReactJs

Javascript 使用refs聚焦输入的ReactJs,javascript,reactjs,Javascript,Reactjs,我尝试使用refs is ReactJs,通过单击按钮来聚焦文本框 但我收到以下错误消息:- bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined 源代码 class FocusText extends Component{ handleClick(){ this.refs.myTextInput.focus(); } r

我尝试使用refs is ReactJs,通过单击按钮来聚焦文本框

但我收到以下错误消息:-

bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined
源代码

class FocusText extends Component{

        handleClick(){
            this.refs.myTextInput.focus();
        }

        render(){
            return(
                <div>
                    <input type="text" ref="myTextInput"/>
                    <input type="button"
                           value="Focus the text input"
                           onClick={this.handleClick.bind(this)}/>
                </div>
            );
        }
    }

    React.render(<FocusText/>, document.getElementById('root'));
类FocusText扩展组件{
handleClick(){
this.refs.myTextInput.focus();
}
render(){
返回(
);
}
}
React.render(,document.getElementById('root'));
已弃用,根据文档

我们建议不要这样做,因为字符串引用有一些问题,是吗 被认为是遗产,并可能在未来某一天被移除 释放

你应该改用

将引用指定给实例上的属性:

<input type="text" ref={(input) => { this.myTextInput= input; }} />
尝试使用回调:

class FocusText extends React.Component{

        handleClick(){
            console.log(this.focus)
        }

        render(){
            return(
                <div>
                    <input type="text" ref={ focus => this.focus = focus }/>
                    <input type="button"
                           value="Focus the text input"
                           onClick={this.handleClick.bind(this)}/>
                </div>
            );
        }
    }

    React.render(<FocusText/>, document.getElementById('app'));
类FocusText扩展了React.Component{
handleClick(){
console.log(this.focus)
}
render(){
返回(
this.focus=focus}/>
);
}
}
React.render(,document.getElementById('app'));
从React文档:

如果您以前使用过React,您可能会熟悉一个较旧的API,其中ref属性是一个字符串,如“textInput”,DOM节点是作为this.refs.textInput访问的。我们建议不要这样做,因为字符串引用有一些问题,被认为是遗留的,并且可能在将来的某个版本中被删除。如果当前正在使用this.refs.textInput访问refs,我们建议改为使用回调模式


正如其他人所说,字符串引用已被弃用

不过,它现在仍然可以使用字符串ref,但在最后一行中,我将使用
ReactDOM

ReactDOM.render(<FocusText />, document.getElementById("root"));
ReactDOM.render(,document.getElementById(“根”);
在代码中,您没有使用ReactDOM。这有什么原因吗


请参见

也请参见此我正在阅读一本教科书,它从未声明要引用它,如果您没有质疑此id,它将被永久保留!谢谢太棒了!:)我很高兴workedIt失败了,因为我使用的是React.render,而不是“React dom”中的ReactDOM.render:-(
ReactDOM.render(<FocusText />, document.getElementById("root"));