首页 > 解决方案 > 自动焦点属性在 React Native 的文本输入组件中不起作用

问题描述

我正在制作一个搜索栏,我希望他们在单击搜索按钮后打开键盘,但是 TextInput 的 autoFocus 属性不起作用。我究竟做错了什么?

这是代码:

const SearchBar = () => {
    return (
        <View style={{ flex: 1 }}>
            <TextInput placeholder="Search"
                style={{ width: Dimensions.get('screen').width, height: 50, borderWidth: 1, 
                borderRadius: 20 }}
                autoFocus={true} 
            /> 
        </View>
     )
}

const Search = () => {
    return (
        <TouchableWithoutFeedback onPress={()=>Keyboard.dismiss()} >
            <SearchBar />
       </TouchableWithoutFeedback>
    )
 }

标签: react-nativesearchkeyboardtextinputautofocus

解决方案


嗯,理想情况下,autoFocus 应该可以安装这个 comp。

如果不是,解决方法是显式添加一个 ref 并聚焦它

class ABC extends .. {

constructor(props){
...
this.textInput = React.createRef();

}

componentDidMount(){
this.textInput.current.focus();
}

 SearchBar = () => {
    return (
        <View style={{ flex: 1 }}>
            <TextInput placeholder="Search"
                style={{ width: Dimensions.get('screen').width, height: 50, borderWidth: 1, 
                borderRadius: 20 }}
                autoFocus={true} 
ref={this.textInput}
            /> 
        </View>
     )
}

}

推荐阅读