简体   繁体   中英

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

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:

MessageList.js:65 Uncaught TypeError: Cannot read property 'updateApply' of undefined

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

        }
    }));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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