【问题标题】:Auto Focus Property is not working in Text Input Component on React Native自动焦点属性在 React Native 的文本输入组件中不起作用
【发布时间】:2021-10-15 10:28:02
【问题描述】:

我正在制作一个搜索栏,我希望在单击“搜索”按钮后打开键盘,但是 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-native search keyboard textinput autofocus


    【解决方案1】:

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

    如果不是,解决方法是显式添加一个 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>
         )
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 2012-10-25
      • 2017-09-11
      • 1970-01-01
      • 2018-08-07
      • 2019-07-04
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多