简体   繁体   中英

Keyboard not being dismissed with Keyboard.dismiss in React Native

I'm looking to dismiss the keyboard when the user clicks on anywhere outside the keyboard or the input, but the keyboard is not being dismissed when I click elsewhere:

        <TouchableWithoutFeedback style={styles.container} onPress={Keyboard.dismiss}>
            <View style={styles.inputContainer}>
                <TextInput
                    placeholder="Search Term"
                    style={styles.input}
                    onChangeText={setSearch}
                    value={search}
                    returnKeyType="search"
                    onSubmitEditing={handleSubmit}
                />
            </View>
        </ TouchableWithoutFeedback>

The styling is pretty standard:

   container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    inputContainer: {
        position: 'absolute',
        top: stackHeaderHeight + 10,
        height: height * .1,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },

You need to change your onPress code of TouchableWithoutFeedback

<TouchableWithoutFeedback style={styles.container} onPress={()=> Keyboard.dismiss()}>

        </ TouchableWithoutFeedback>

Sample working code.

render() {
return (
  <TouchableWithoutFeedback onPress={()=>Keyboard.dismiss()} >
    <View style={{ flex: 1 }}>
      <TextInput returnKeyType="search" style={{borderWidth:1,borderColor:'grey',marginTop:100,height:50,marginHorizontal:50}}/>
    </View>
  </TouchableWithoutFeedback>
);
}

I think you have a problem with your style properties. Please check on your container and inputcontainer style properties. If you have any ScrollView in your render method add following

<ScrollView keyboardShouldPersistTaps='always'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM