ReactNative 中TextInput刚进入页面获取焦点

需求:进入ReactNative页面中,页面上含有TextInput控件,则TextInput 获取焦点,将键盘弹出需求。

TextInput 页面出现的时期
1、页面刚渲染出来就出现TextInput。
2、页面中通过设置state值后页面,渲染出TextInput。

针对于第一中情况,查看RN中 TextInput属性 可以看到 autoFocus该属性
如果为true,在componentDidMount后会获得焦点。默认值为false。

第二种情况,因为componentDidMount 在页面生成时只执行一次。通过设置state值后,渲染出TextInput 并不能通过设置autoFocus来获取焦点。

通过refs来实现 focus();

具体参考代码如下:

 this.updateText(text)} ref='textInputRefer'
             placeholder={'请输入内容'}/>

componentDidUpdate(){
if (this.refs.textInputRefer != undefined) {
        this.refs.textInputRefer.focus();
}
},

你可能感兴趣的:(ReactNative 中TextInput刚进入页面获取焦点)