【问题标题】:Why does the "Enter" key not trigger onKeyPress in React Native?为什么 React Native 中的“Enter”键不会触发 onKeyPress?
【发布时间】:2018-05-29 12:25:41
【问题描述】:

我在我的文本输入中添加了一个 onKeyPress 事件侦听器,这样当用户在手机键盘上单击完成或转到或“输入”时,它就会调用我的 searchProducts 函数。我希望有一个 onSubmit 类型的事件侦听器选项,但找不到类似的东西,所以现在我只需要检查每个按下的键。当按下诸如“j”或“x”之类的字符键时,它会触发 onKeyPress 事件并调用我的 searchProducts 函数。但是,当我用鼠标单击完成或按键盘上的回车键时,什么也没有发生。如何让它触发 onKeyPress 事件监听器??

searchProducts = (e) => {
    if (e.nativeEvent.key == "Enter"){
        this.props.searchFunc(this.state.term);
    }
}

<TextInput 
    ref='searchBar'
    style={styles.searchInput} 
    placeholder={placeholder}

    onChangeText={this.searchSuggestions}
    onKeyPress={this.searchProducts.bind(this)}
    underlineColorAndroid="transparent" 
/>

【问题讨论】:

  • 提示:当你将searchProducts方法定义为箭头函数searchProducts = (e) =&gt; 时,你可以将其作为onKeyPress={this.searchProducts)使用,无需绑定
  • 与其问same question 两次,不如考虑在第一个问题中添加赏金以吸引更多答案。

标签: android react-native onkeypress


【解决方案1】:

您可以使用onSubmitEditing,即:

文本输入的提交按钮时调用的回调 按下。如果指定了 multiline={true} 则无效。

按下键盘上的“完成”按钮后会调用它。

【讨论】:

  • 它有效,但只有当我写 onSubmitEditing={() =&gt; Keyboard.dismiss()} 时(键盘是从 react-native 导入的。
【解决方案2】:

onKeyPress 应该在您按下返回键时触发,检查您在此页面中是否有另一个事件取消触发此事件 如果是,请使用

event.stopPropagation()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 2019-12-16
    • 2020-07-03
    • 2019-06-02
    • 1970-01-01
    相关资源
    最近更新 更多