如何在 TextInput 中按 'Enter' 调用函数 - React Native

How to call function on 'Enter' press in TextInput - React Native

我正在尝试制作搜索栏。我希望用户在 TextInput 中输入内容,当用户按下 'Enter' 时,我想调用我的函数。

<TextInput
//here when user press enter call function()
style={styles.searchStyle}
allowFontScaling={false}
placeholder="Search" 
onChangeText={(val) => {setSearch(val)}}
/> 

我尝试了 onSubmitEditing 但它不起作用。

import React, { Component } from 'react' import {TextInput} from 'react-native'

const Trial =()=>{
    const onSubmitted=()=>{
        console.log('Submitted')
      }
return(
    <TextInput
//here when user press enter call function()
// style={styles.searchStyle}
allowFontScaling={false}
placeholder="Search" 
onSubmitEditing={()=>onSubmitted()}

/>
)
}

export default Trial

onSubmitEditing 运行良好,希望对您有所帮助

如果您在 TextInput 中使用 mutiline={true},例如 <TextInput multiline={true} /> onSubmitEditing 将不起作用,而是移至 nextLine。

我正在做一个解决方法,所以基本上我检查用户是否输入了下一行,如果是,调用提交函数并关闭键盘,你可以从 react-native 导入 {Keyboard}

<TextInput onChangeText={(txt) => {
        if (/\n/.test(txt)) {
         //call submit function here
          Keyboard.dismiss()
          return
        } else {
          //do something here
        }
        
      }} />