我正在使用React Native Gifted Code。
这是下面提供的我的代码段:
constructor(props) {
super(props);
this.state = {
message: [{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
}],
}
}
componentDidMount() { }
onSend(messageSend = []) {
this.setState(
previousMessages => ({
message: GiftedChat.append(previousMessages, messageSend)
})
);
}
render() {
const chat = <GiftedChat
messages={this.state.message}
onSend={(messageSend) => this.onSend(messageSend)}
user={{
_id: 1,
}}
/>;
if (Platform.OS === 'android') {
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
behaviour="padding"
keyboardVerticalOffset={30}
enabled
>
{chat}
</KeyboardAvoidingView>
);
}
}
但是,在转换为类组件之后,我并没有获得理想的结果。 (something similar to this)
问题是,发送新邮件时,它会“替换”发件人的 消息和我的最新消息。
答案 0 :(得分:0)
这是基于您的代码的类组件的完整代码
import React from 'react';
import {KeyboardAvoidingView, Platform} from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
export default class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
message: [{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
}],
}
}
//send message will no longer overlap/replace 'hello developer'
onSend(messageSend = []) {
this.setState(
previousMessages => ({
message: GiftedChat.append(previousMessages.messsage, messageSend)
})
);
}
render() {
const chat = <GiftedChat
messages={this.state.message}
onSend={(messageSend) => this.onSend(messageSend)}
user={{
_id: 1,
}}
/>;
if (Platform.OS === 'android') {
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
behaviour="padding"
keyboardVerticalOffset={30}
enabled
>
{chat}
</KeyboardAvoidingView>
);
} else {
return chat
}
}
}
您也可以在expo
中检查样本上述代码的输出:
答案 1 :(得分:0)
显然,我不得不添加previousMessages.messsage
而不是previousMessages
。
解决方案:
//send message will no longer overlap/replace 'hello developer'
onSend(messageSend = []) {
this.setState(
previousMessages => ({
message: GiftedChat.append(previousMessages.messsage, messageSend)
})
);
}