[英]props destructuring in react
I have component props looks like我有组件道具看起来像
**props**
{
banner : {
logo: "...",
banner: "..."
},
content,
...
}
I grab this props like this我像这样抓住这个道具
const MyComponent = (props) => {
const {
banner: { logo, title },
content
} = props;
...
function someFunction(){
if( banner.logo) {. // <- banner is undefined
if(title) // <- this title works
}
...
}
...
}
I tried to destructuring props object and use all of these banner, content, logo, title我试图解构道具 object 并使用所有这些横幅、内容、徽标、标题
but compiler complains banner as undefined.但编译器抱怨横幅未定义。 Am I doing wrong about destructuring?我在解构方面做错了吗?
When you are destructuring objects like the following, only logo
, title
and content
are unpacked.当你像下面这样解构对象时,只有logo
、 title
和content
被解包。
const {
banner: { logo, title },
content
} = props;
That's why inside someFunction
in your question, you could just do:这就是为什么在你的问题中的someFunction
中,你可以这样做:
function someFunction() {
if (logo) {
...
if (title) {
...
}
}
}
If you also want to use the variable banner
, you have to do the following:如果您还想使用变量banner
,则必须执行以下操作:
const { banner, content } = props;
const { logo, title } = banner;
Read more about Destructuring assignment阅读有关解构分配的更多信息
Simple, you are not taking the banner variable from the props actually, you are taking title and logo instead.很简单,您实际上并没有从道具中获取横幅变量,而是取而代之的是标题和徽标。
You can do this:你可以这样做:
const MyComponent = (props) => {
const {
banner,
content
} = props;
...
function someFunction(){
if( banner.logo) {
if(banner.title)
}
...
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.