javascript - ReactJs 使用 refs 来聚焦输入

标签 javascript reactjs

<分区>

我正在尝试使用 refs 是 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'));

最佳答案

String refs已弃用,根据文档...

We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

你应该使用 callback ref相反。

将 ref 分配给实例的属性:

<input type="text" ref={(input) => { this.myTextInput= input; }} />

使用引用:

handleClick(){
    this.myTextInput.focus(); // note that refs is no longer necessary 
}

关于javascript - ReactJs 使用 refs 来聚焦输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45127636/

相关文章:

javascript - Angular 不适用于 Express 和 Pug

javascript - jQuery 的多个 div 创建/销毁错误

reactjs - 使用 Route render 时,ReactComponent 没有与类型 'IntrinsicAttributes & { children?: ReactNode; }' 相同的属性

javascript - 捆绑失败 : Error: Cannot find module 'babel-preset-react-native' from '/workspace/reactnative' '

javascript - 无法在 React 表单上输入我的第二个字段。为什么会发生这种情况?

javascript - 尝试在按钮单击时打开模式

javascript - 在可编辑网格中,如何使Ext组合框在选择项目时立即结束编辑模式?

javascript - 如何从浏览器中使用默认应用程序打开本地文件?

javascript - 如何在 ember.js 的模式对话框中打开路线?

javascript - react 值返回为未定义