React Native TextInput onSubmitEnding不起作用 - 创建合成事件

问题描述 投票:0回答:2

期望的国家

我在react native中有两个文本输入字段,每个字段的最终输入需要附加到一个数组。因此我正在使用onSubmitEditing,否则如果我使用onChangeText,用户输入的每个字符都会附加到数组中。

错误

onSubmitEditing调用父组件中的函数,并给出以下错误

“ExceptionsManager.js:84警告:出于性能原因,重复使用此合成事件。如果您看到这个,则在已发布/无效的合成事件上访问属性nativeEvent。这将设置为null。如果您必须保留原始合成事件,使用event.persist()。“

我尝试将该函数移动到同一个文件,这是不理想的但我仍然得到这个数组而不是文本输入。数组中似乎没有任何有用的东西。

“[SyntheticEvent]”

子组件

 <TextInput
    style={styles.signupInput}
    onSubmitEditing={(val) => this.props.saveFriends(val)}
    autoCorrect={false}
    autoFocus={true}
    placeholder={'friend one'}
    placeholderTextColor={'white'}
  />
  <TextInput
    style={styles.signupInput}
    onSubmitEditing={(val) => this.props.saveFriends(val)}
    autoCorrect={false}
    autoFocus={true}
    placeholder={'friend two'}
    placeholderTextColor={'white'}
  />

父组件

  saveFriends = (val) => {
    this.setState({
      friends: [
        ...this.state.friends,
        val
      ]
    })
}

任何帮助将不胜感激!

javascript reactjs react-native textinput
2个回答
3
投票

因此,当您使用onSubmitEditing属性时,传递给回调的参数是一个事件对象。为了访问您的文本并将其保存到阵列,您有两个解决方案:

第一个解决方案,访问事件的正确属性

<TextInput
    style={styles.signupInput}
    onSubmitEditing={(event) => this.props.saveFriends(event.nativeEvent.text)}
    autoCorrect={false}
    autoFocus={true}
    placeholder={'friend one'}
    placeholderTextColor={'white'}
  />

其次,使用ButtononChangeText在组件状态中保存输入的值:

<TextInput
    style={styles.signupInput}
    onChangeText={(val) => this.setState({val})}
    autoCorrect={false}
    autoFocus={true}
    placeholder={'friend one'}
    placeholderTextColor={'white'}
  />
  
<Button
  onPress={() => this.props.saveFriends(this.state.val)}
/>

希望这可以帮助。


0
投票

试试这个

onSubmitEditing={() => this.props.saveFriends(val)}
© www.soinside.com 2019 - 2024. All rights reserved.