需求:進(jìn)入ReactNative頁面中,頁面上含有TextInput控件,則TextInput 獲取焦點(diǎn),將鍵盤彈出需求。
TextInput 頁面出現(xiàn)的時期
1、頁面剛渲染出來就出現(xiàn)TextInput。
2、頁面中通過設(shè)置state值后頁面,渲染出TextInput。
針對于第一中情況,查看RN中 TextInput屬性 可以看到 autoFocus該屬性
如果為true,在componentDidMount后會獲得焦點(diǎn)。默認(rèn)值為false。
第二種情況,因?yàn)閏omponentDidMount 在頁面生成時只執(zhí)行一次。通過設(shè)置state值后,渲染出TextInput 并不能通過設(shè)置autoFocus來獲取焦點(diǎn)。
通過refs來實(shí)現(xiàn) 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={'請輸入內(nèi)容'}/>
componentDidUpdate(){
if (this.refs.textInputRefer != undefined) {
this.refs.textInputRefer.focus();
}
},