【问题标题】:Clearing a Textinput using a TouchableOpacity without dismissing the keyboard?在不关闭键盘的情况下使用 TouchableOpacity 清除 Textinput?
【发布时间】:2018-01-18 12:57:02
【问题描述】:

我想建立一个超级简单的聊天。 为此,需要一个 TextInput 和一个 TouchableOpacity 来发送消息并 清除文本输入。

问题:当我发送消息时,Textinput 被清除但当再次开始写入时,旧文本再次复制到 Textinput 中(+ 新字符)。 但是,如果在发送和清除一切正常后关闭键盘 完全没问题。

有什么方法可以用 TouchableOpacity 完全清除 TextInput?

下面是代码,我自己尝试了几次,但都没有奏效。 提前致谢,

马菲尼斯

      <View style={{flexDirection: 'row'}}>
      <TextInput
      placeholder="Schreibe eine Nachricht"
      onChangeText={(text) => this.setState({newMsg : text})}
      style={{width: 300}}
      ref={'ref1'}
      />
      <TouchableOpacity
      onPress={this.sendMessage}
      >
      <Text> --> </Text>
      </TouchableOpacity>
      </View>
      

sendMessage = () => {
  this.state.MsgData.push({msg: this.state.newMsg, id: this.props.global.userId, timestamp: 8888});
  this.refs['ref1'].clear();
  this.setState({newMsg: ""});
  //this.refs['ref1'].setNativeProps({text: ''})
  //Keyboard.dismiss();

}
  1. 列表项

【问题讨论】:

    标签: react-native textinput expo touchableopacity


    【解决方案1】:

    使用defaultValue 属性设置状态值(https://facebook.github.io/react-native/docs/textinput.html#defaultvalue

    <TextInput
      placeholder="Schreibe eine Nachricht"
      onChangeText={(text) => this.setState({newMsg : text})}
      style={{width: 300}}
      ref={(input) => this.ref1 = input}
      defaultValue={this.state.newMsg}
    />
    

    完整实现请参见此示例:https://snack.expo.io/SkuH8hKPb

    【讨论】:

    • 不应该只是价值吗?
    • 首先感谢快速响应:代码示例几乎可以正常工作,但您必须在消息文本后添加一个空格(否则当我开始时,最后一个单词或字符仍会复制到 textinput 中再写)。有没有什么办法解决这一问题? (手动添加空格不起作用)。
    猜你喜欢
    • 2022-01-12
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2011-07-17
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多