如何在带有Redux的React Native中清除发送按钮上的TextInput

时间:2019-10-16 08:42:27

标签: reactjs react-native redux react-native-textinput

我正在使用带redux的react native开发聊天应用,其中消息通过发送按钮发送。但是,每当我发送有关按下“发送”按钮的消息时,TextInput都不会清除。 我想在点击发送按钮时清除TextInput字段。在这里,我在redux中工作,所以我不想将statevalue一起使用。

这是代码:

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>

2 个答案:

答案 0 :(得分:1)

您可以尝试在发送邮件后清除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('');   
}

答案 1 :(得分:1)

您可以使用ref清除Chat中的值。

在构造函数中添加新的引用

constructor(props) {
  super(props);
  this.textInput = React.createRef();
}

ref传递到MessageInput

render() {
  ...
  <MessageInput 
    onChangeText={text => this.message(text)}
    onPress={this.onSend }
    ref={this.textInput}
  />
  ...  
}

修改MessageInput(我将假定它是一个功能组件)

const MessageInput = (props, ref) => (
  ...
  <TextInput style={inputs}
    placeholder="Write a message..."
    onChangeText={onChangeText}
    ref={ref}
  />
  ...
)

最后,切换回Chat组件并更新onSend

onSend = () => {
  const { userId , receiverId, text } = this.props;
  this.props.sendMessage({userId , receiverId, text});
  this.textInput.current.clear(); // Clear the text input
}