[英]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.我正在尝试将数据“template_titles”传递给我的子组件并将它们显示在选项下拉列表中。 Just trying to console.log the data to make sure it's passing.
只是试图 console.log 数据以确保它通过。 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.当您的组件是 function 而不是 class 时,您不能使用
this
。
And when passing it, you need to drop the this
too:当通过它时,你也需要删除
this
:
<ComposeEmailForm
handleCompose={this.sendNewEmail}
template_titles={template_titles}
/>
since you define it as such in your render
function.因为您在
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:实际上,在 function 组件中,您并不会太使用
this
,尤其是当您在参数的括号中破坏props
时,您可以访问您的道具,如下所示:
export default function ComposeEmailForm({ handleCompose, template_titles }) {
console.log(template_titles, handleCompose);
return (
<div className='container'></div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.