首页 > 解决方案 > 如何使用 redux 在 React Native 中清除发送按钮上的 TextInput

问题描述

我正在使用带有 redux 的 react native 开发聊天应用程序,其中消息通过发送按钮发送。但是,每当我在点击发送按钮时发送消息时,TextInput都不会清除。我想TextInput在点击发送按钮时清除该字段。在这里,我在 redux 工作,所以我不想使用statewith value

这是代码:

class Chat extends Component {

  componentWillMount() {
    this.props.fetchChat(this.props.receiverId);  
}

message(text) {
  this.props.writeMsg(text);    
}
onSend = () => {

  const { userId , receiverId, text } = this.props;
  this.props.sendMessage({userId , receiverId, text});
}

  render() {

    return (
      <View style={{ flex: 1 }}>

            <FlatList 
              inverted={-1}
              style={styles.list}
              extraData={this.props}
              data={this.props.convo}
              keyExtractor = {(item) => {
                return item.id;
              }}
              renderItem=   
              <ChatItem value={this.renderItem} />           
              />

             <MessageInput 
             onChangeText={text => this.message(text)}
             onPress={this.onSend }
            />          
      </View>
    );
  }
}

这是组件 MessageInput 的代码:

  <View style={inputContainer}>
            <TextInput style={inputs}
                placeholder="Write a message..."
                onChangeText={onChangeText}
              />
          </View>

            <TouchableOpacity style={btnSend} onPress={onPress }>
              <Icon
            name='send'
            type='MaterialIcons'
            color='#fff'
            style={iconSend}
            />  
            </TouchableOpacity>

标签: reactjsreact-nativereduxreact-native-textinput

解决方案


您可以尝试text在发送消息后清除该属性,(如果 text 属性是在 中呈现的内容TextInput):

onSend = () => {

 const { userId , receiverId, text } = this.props;
 this.props.sendMessage({userId , receiverId, text});
 this.message('');
}

或者

 onSend = () => {

  const { userId , receiverId, text } = this.props;
  this.props.sendMessage({userId , receiverId, text});
  this.props.writeMsg('');   
}

推荐阅读