我正在为聊天创建一个界面,我有一个问题是要正确清除textInput的字段。
这是我目前的代码
export default class Chat extends React.Component{
constructor(props){
super(props)
this.state = {
text: '',
disabled: true,
messages: [
{
id:'1',
text: 'Hello',
avatar: 'http://image.noelshack.com/fichiers/2016/47/1480031586-1474755093-risitas721.png',
author: {
avatar: 'http://image.noelshack.com/fichiers/2016/47/1480031586-1474755093-risitas721.png',
username: 'Dr Risitas'
}
},
{
id:'2',
text:'How are you ?',
author : {
avatar: 'http://image.noelshack.com/fichiers/2016/47/1480031586-1474755093-risitas721.png',
username:'Dr Risitas'
}
}
],
}
}
//Checking input text before sending
onTyping(text) {
if(text && text.length >= 2) {
this.setState({
disabled: false,
text
})
}
else {
this.setState({
disabled: true
})
}
}
//Clear input text when send btn is pressed
onSendBtnPressed = () => {
this.textInput.clear();
this.setState({disabled: true});
}
//Render each item of Flatlist
renderChatItem = ({item}) => {
//return <Text> {item.text}</Text>
return <ChatItem message={item} />
}
//Key for data in FlatList component
keyExtractor = (item, index) => index;
render() {
//extra style for sending button
const extraBtnStyle = this.state.disabled ? styles.disabledBtn : styles.enabledBtn;
//Different behavior to avoid the view when the keyboard is opened
let behavior ='';
if (Platform.OS == 'ios'){
behavior = 'padding';
}
return(
<View style={styles.container}>
<Header
centerComponent={{text: 'I Feel', style: { color: '#fff', fontSize: 20} }}
containerStyles={{height: 56}} />
<FlatList
data={this.state.messages}
renderItem={this.renderChatItem}
keyExtractor={this.keyExtractor}
inverted
/>
<KeyboardAvoidingView behavior={behavior}>
<View style={styles.inputBar}>
<TextInput style={styles.textBox}
style={styles.textBox}
multiline
defaultHeight={30}
onChangeText={(text) => this.onTyping(text)}
ref = {(input) => { this.textInput = input; }}
/>
<TouchableHighlight
style = {[styles.sendBtn, extraBtnStyle]}
disabled = {this.state.disabled}
onPress = {this.onSendBtnPressed}>
<Text style={{color: '#fff'}}> Send </Text>
</TouchableHighlight>
</View>
</KeyboardAvoidingView>
</View>
);
}
}
问题是当按下发送按钮时,文本消失得很好,但是如果我在按下按钮后继续写,则旧消息与我正在写的新消息连接。为了避免这种情况,我必须单击“发送”按钮,然后单击文本字段,然后我可以编写新消息而不进行任何连接
看起来我们需要重新关注textinput,但我不知道该怎么做。我希望我已经清楚了,谢谢你!
使用TextInput
清除.clear()
只清除它显示的内容你还需要清除与你的state
相关的潜在TextInput
。
onSendBtnPressed = () => {
this.textInput.clear();
this.setState({disabled: true, text: ''}); // clear the text value
}
试试this.textInput.current.clear()
谢谢你的答案,但我设法解决了这个问题。
实际上它不是代码的问题,但它是默认由三星键盘引起的。他每次都发出旧信息。所以我通过使用谷歌键盘解决了这个问题。
因此,如果有人遇到同样的问题,只需更换键盘即可。