我正在使用带redux的react native开发聊天应用,其中消息通过发送按钮发送。但是,每当我发送有关按下“发送”按钮的消息时,TextInput
都不会清除。
我想在点击发送按钮时清除TextInput
字段。在这里,我在redux中工作,所以我不想将state
与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>
答案 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
}