[英]React - this is undefined inside component
我遇到問題,當我將值從子級傳遞給父類時,它起作用了,但是當我想將其從父級推給“祖父母”時,它告訴我“ this”是未定義的,並且我不能將function傳遞為“ function = { this.functionName}”
這是使我麻煩的組件:
class MessageList extends Component {
constructor (props) {
super(props);
this.state = {
applyFor: ''
}
this.updateApply = this.updateApply.bind(this);
}
updateApply = (posName) => {
this.setState({
applyFor: posName
})
}...
這是我的渲染功能
render() {
return(
this.props.messages.map(function(message, index){
if(message.type === 'out') {
if(message.qType === 'quick reply'){
return (
<React.Fragment>
<BotTextMessage key={index} message={message.message.text} />
<FadeIn>
<QuickReplyWrapper key={index} options={message.message.options} />
</FadeIn>
</React.Fragment>
);
} else {
return <BotTextMessage key={index} message={message.message.text} />;
}
} else {
// console.log(this)
return <OpenPositionWrapper updateApply={this.updateApply}/>
}
}));
}
當我登錄時,它是未定義的,對於“ updateApply”,它給我:
MessageList.js:65未被捕獲的TypeError:無法讀取未定義的屬性“ updateApply”
您可以嘗試以下方法:
render() {
return(
this.props.messages.map((message, index) => {
if(message.type === 'out') {
if(message.qType === 'quick reply'){
return (
<React.Fragment>
<BotTextMessage key={index} message={message.message.text} />
<FadeIn>
<QuickReplyWrapper key={index} options={message.message.options} />
</FadeIn>
</React.Fragment>
);
} else {
return <BotTextMessage key={index} message={message.message.text} />;
}
} else {
// console.log(this)
return <OpenPositionWrapper updateApply={this.updateApply}/>
}
}));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.