[英]Use Props Callback with react native
I would like to know how can I pass callback with react native please. 我想知道如何通过react native传递回调。
Currently I have 3 components : 目前,我有3个组成部分:
MessageTypeText.js -> MessageButtons.js -> MessageButton.js MessageTypeText.js-> MessageButtons.js-> MessageButton.js
1 MessageButton.js 1个MessageButton.js
export default class MessageButton extends React.Component {
clickButton(button) {
console.log('message button');
this.props.callBackFunction('PAYLOAD' , button.payload);
}
render() {
let button = this.props.button;
return (
<TouchableOpacity onPress={() => this.clickButton(button)}>
<Text>
{ button.title }
</Text>
</TouchableOpacity>
);
}
}
2 MessageButtons.js 2个MessageButtons.js
export default class MessageButtons extends React.Component {
sendMessageToAPI(messageType, data) {
console.log('message buttons');
this.props.callBackMessageButtons(messageType , data);
}
renderButtons(buttons) {
return(buttons.map((button, indexButton) => {
return <MessageButton key={indexButton}
button={button}
callBackFunction={this.sendMessageToAPI} />
}))
}
...
}
3 MessageTypeText.js 3 MessageTypeText.js
export default class MessageTypeText extends React.Component {
sendMessageToAPI(messageType, data) {
console.log('message type text');
//this.props.callBackFunction(messageType , data);
}
renderButtons(message) {
if(...){
return (<MessageButtons buttons={message.attachment.payload.buttons}
callBackMessageButtons={this.sendMessageToAPI} />)
}
}
...
}
When I click on TouchableOpacity in component MessageButton.js (more deeply), I see in my console : 当我单击组件MessageButton.js中的TouchableOpacity(更深入)时,在控制台中看到了:
message button, message buttons 信息按钮,信息按钮
but I don't see : 但我看不到:
message type text 讯息类型文字
And I have this error : 我有这个错误:
Cannot read property 'callBackMessageButtons' of undefined (MessageButtons.js (line 10) 无法读取未定义的属性“ callBackMessageButtons”(MessageButtons.js(第10行)
I can execute this.props.callBackMessageButtons(messageType , data); 我可以执行this.props.callBackMessageButtons(messageType,data); in MessageButtons.js 在MessageButtons.js中
I use the arrow function in my render, but I have always this error. 我在渲染器中使用了箭头功能,但始终出现此错误。
Do not forget about binding your callbacks. 不要忘记绑定回调。 Or just use arrow function: 或者只是使用箭头功能:
sendMessageToAPI = (messageType, data) => {
console.log('message buttons');
this.props.callBackMessageButtons(messageType , data);
}
That's necessary to make this
work in the callback as you would expect. 如您所料, this
对于在回调中进行this
工作是必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.