简体   繁体   中英

Passing data from parent class to child function -props undefined

I'm trying to pass data 'template_titles' to my child component and display them in an option dropdown. Just trying to console.log the data to make sure it's passing. Currently running into an issue where property props are undefined.

Parent Component

    render() {
    if (!this.props.show) {
        return null;
    }

    const template_titles = this.state.email_template.map((a) => a.title);
    console.log(template_titles);

    return (
        <div className='compose-email'>
            <div className='directory'>
                <div className='background' />
                <div className='box'>
                    <ion-icon
                        id='close-email'
                        name='close'
                        onClick={this.onClose}
                    ></ion-icon>
                    <ion-icon
                        id='square-email'
                        name='square'
                        onClick={this.onClose}
                    ></ion-icon>
                    <h1 className='candidate-name-compose-email'>
                        Candidate Name
                    </h1>
                    <hr></hr>
                    <h1 className='compose-email-title-compose-email'>
                        Compose Email
                    </h1>
                    <ComposeEmailForm
                        handleCompose={this.sendNewEmail}
                        template_titles={this.template_titles}
                    />
                </div>
                <ToastContainer className='toast-container' />
            </div>
        </div>
    );
}

Child Component

    export default function ComposeEmailForm({ handleCompose }) {

console.log(this.props.template_titles);

return (
    <div className='container'></div>
);

}

Try this instead:

export default function ComposeEmailForm({ handleCompose, template_titles }) {

console.log(template_titles);

return (
    <div className='container'></div>
);

You can't use this when your component is a function and not a class.

And when passing it, you need to drop the this too:

 <ComposeEmailForm
    handleCompose={this.sendNewEmail}
    template_titles={template_titles}
 />

since you define it as such in your render function.

Actually, in the function component, you don't too use this , especially when you destruct props in the parentheses of the argument, then you can access to you props like below:

export default function ComposeEmailForm({ handleCompose, template_titles }) {

  console.log(template_titles, handleCompose);

  return (
    <div className='container'></div>
  );
};

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