美文网首页
ReactNative 中TextInput刚进入页面获取焦点

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

作者: TaoGeNet | 来源:发表于2017-08-14 14:36 被阅读991次

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

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

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

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

通过refs来实现 focus();

具体参考代码如下:

<TextInput autoFocus={true} multiline={true} clearButtonMode={'while-editing'}
             style={{
                              fontSize: 14,
                              marginTop: 0,
                              flex: 1,
                              backgroundColor: '#ffffff'
                          }} 
             onChangeText={(text) => this.updateText(text)} ref='textInputRefer'
             placeholder={'请输入内容'}/>

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

相关文章

网友评论

      本文标题:ReactNative 中TextInput刚进入页面获取焦点

      本文链接:https://www.haomeiwen.com/subject/bsjurxtx.html