[英]React Native: Functional Component to Class Component
I am using React Native Gifted Code .我正在使用React Native 天才代码。
I am trying to convert the following example to class component:我正在尝试将以下示例转换为类组件:
And here's is my code snippet provided below:这是我在下面提供的代码片段:
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>
);
}
}
However, after converting to class component I am not the getting the desired outcome.但是,在转换为类组件后,我并没有得到想要的结果。 ( something similar to this ) (类似的东西)
The issue is when sending a new message, it's 'replacing' the sender's message with my latest message.问题是在发送新消息时,它用我的最新消息“替换”了发件人的消息。
Here is the full code for class component based on your code这是基于您的代码的类组件的完整代码
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
}
}
}
You can also the check the sample in expo您也可以在世博会上查看样品
Output of the above code:上面代码的输出:
Apparently I had to add previousMessages.messsage
instead of previousMessages
.显然我不得不添加previousMessages.messsage
而不是previousMessages
。
SOLUTION:解决方案:
//send message will no longer overlap/replace 'hello developer'
onSend(messageSend = []) {
this.setState(
previousMessages => ({
message: GiftedChat.append(previousMessages.messsage, messageSend)
})
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.