0

我正在使用带有 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>
4

2 回答 2

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('');   
}
于 2019-10-16T08:58:48.760 回答
1

您可以使用 aref清除 中的值Chat

在构造函数中添加一个新的 ref

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
}
于 2019-10-16T09:46:15.230 回答