我正在开发聊天应用程序。当我单击发送按钮时,如果使用setState清除代码中的输入框,则在发送消息后,输入框会变得非常拥塞。如果在发送消息后我没有清除输入框,则不会出现此类问题。这个问题困扰了我很长时间。希望我能得到您的帮助。谢谢。
反应性:0.55.4 平台:Android
聊天页面代码:
render() {
return (
<KeyboardAvoidingView
behavior='position' contentContainerStyle={{flex: 1}} style={{flex: 1,backgroundColor:'#eeeeee'}}
keyboardVerticalOffset={px2dp((Platform.OS==='ios'?148:-632))}>
<FlatList
ref='flatList'
style={{}}
data={this.state.msgList}
keyExtractor={item => item.msgId}
renderItem={({index, item}) => this.renderItem(index, item)}
automaticallyAdjustContentInsets={false}
initialNumToRender={8}
>
</FlatList>
<MessageInput onSend={this.onSend} onFocus={this.onFocus}/>
</KeyboardAvoidingView>)
}
消息输入组件代码:
export default class MessageItem extends Component{
constructor(props) {
super(props)
this.state = {
showEmoticons:false,
message:"",
}
}
componentWillReceiveProps(nextProps){
}
shouldComponentUpdate(nextProps,nextState){
return nextState.message!==this.state.message;
}
onChangeText=(message)=>{
this.setState({message:message});
}
//Send message
onSend=()=>{
this.props.onSend&&this.props.onSend(this.state.message);
**this.setState({message:""})**;// if add this line code,input box will change very slow
}
render(){
const msg=this.state.message;
return (<View style={{
padding: px2dp(50),
paddingTop: px2dp(16),
paddingBottom: px2dp(16),
bottom:this.state.showEmoticons?300:0,
height:px2dp(110),
backgroundColor:'#e5e5e7',
flexDirection:'row',
alignItems:'center',
justifyContent:'center'
}}>
<MaterialIcon name="keyboard-voice" size={px2dp(55)} onPress={this.onSearch}
style={{textAlign: "center",marginLeft:10,marginRight:10}} color="#111111"/>
<TextInput ref='msgInput' value={msg} style={{
height: px2dp(80),
borderRadius: px2dp(10),
borderColor:'white',
backgroundColor:'white',
fontSize:12,
lineHeight: px2dp(36),
padding: px2dp(20),
borderWidth: 1,
width:(msg.length>0?(width-px2dp(55)*2-px2dp(119)-50):(width-px2dp(55)*3-50)),
}} placeholder='我来说两句'
multiline={true}
returnKeyType='default'
underlineColorAndroid='transparent'
onChangeText={this.onChangeText}
/>
<SimpleLineIcon name="emotsmile" size={px2dp(55)} onPress={this.onShowEmoticons}
style={{textAlign: "center",marginLeft:10}} color="#111111"/>
{msg.length>0?<TouchableOpacity onPress={this.onSend}>
<View style={styles.sendMsgContainer}><Text style={styles.sendMsgBtn}>发送</Text></View>
</TouchableOpacity>:<AntDesignIcon name="pluscircleo" size={px2dp(55)} onPress={this.onSearch}
style={{textAlign: "center",marginLeft:10,marginRight:10}} color="#111111"/>}
</View>)
}
}
当我使用添加'this.setState({message:“”});'代码添加到onSend函数中,发送消息后,输入框多次被卡住