简体   繁体   English

反应-这在组件内部未定义

[英]React - this is undefined inside component

I ran into problem, when i pass value from child to parent class it works but when i want to push it from parent to 'grandparent' it tells me that 'this' is undefined and i can't pass function as 'function={this.functionName}' 我遇到问题,当我将值从子级传递给父类时,它起作用了,但是当我想将其从父级推给“祖父母”时,它告诉我“ this”是未定义的,并且我不能将function传递为“ function = { this.functionName}”

Here is component that is making me problems: 这是使我麻烦的组件:

class MessageList extends Component {
constructor (props) {
    super(props);
    this.state = {
        applyFor: ''
    }
    this.updateApply = this.updateApply.bind(this);
}

updateApply = (posName) => {
    this.setState({
        applyFor: posName
    })
}...

and this is my render function 这是我的渲染功能

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}/>

        }
    }));

}

when i log this it is undefined and for 'updateApply' it gives me: 当我登录时,它是未定义的,对于“ updateApply”,它给我:

MessageList.js:65 Uncaught TypeError: Cannot read property 'updateApply' of undefined MessageList.js:65未被捕获的TypeError:无法读取未定义的属性“ updateApply”

You can try this: 您可以尝试以下方法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM