Reactjs 解构道具,同时添加道具。-可能吗?
我有一些这样的道具Reactjs 解构道具,同时添加道具。-可能吗?,reactjs,ecmascript-6,Reactjs,Ecmascript 6,我有一些这样的道具 const { header, footer, name, body, title, } = this.props; 所有这些都很好,但有没有一种方法可以在上面的语法中为body指定名称,而不必在以后指定它 差不多 const { header, footer, name, body: {...name}, title, } = this.props; 记住我想保留身体里的东西,但要给它加上鼻涕虫 为主体提供自定义名称: const
const {
header,
footer,
name,
body,
title,
} = this.props;
所有这些都很好,但有没有一种方法可以在上面的语法中为body指定名称,而不必在以后指定它
差不多
const {
header,
footer,
name,
body: {...name},
title,
} = this.props;
记住我想保留身体里的东西,但要给它加上鼻涕虫 为
主体提供自定义名称:
const{
标题,
页脚,
名称
正文:customName,
标题
}=这是道具;
console.log(customName);
将主体
和名称
道具组合成单个主体
常量:
const this.props={
名称:{name1:1,name2:2},
正文:{body1:3,body2:4}
};
常数{
标题,
页脚,
名称
身体,
标题
} = {
…这是道具,
正文:{…this.props.body,…this.props.name}
};
控制台日志(主体);
假设
const this = {
props: {
header: 'header',
footer: 'footer',
name: 'name',
body: 'body',
title: 'title',
}
};
我想这就是你想要实现的
const {
header,
footer,
name,
body,
title,
} = {
...this.props,
body: this.props.name,
//if body is an object, and name is an object, and you want to merge the two you can do:
/**
* body: { ...this.props.body, ...this.props.name }
*/
};
console.log(body); //"name"
但似乎要简单得多
const {
header,
footer,
name,
title,
} = this.props;
const body = this.props.name;
// or if you are merging
/**
* const body = { ...this.props.body, ...name };
*/
但就您的示例而言,在定义(或解构)对象时,不能引用对象中的键
是的,这是给身体一个自定义的名字,但这不是我被问到的,但无论如何,谢谢。我想问的是,我是否可以为body分配额外的属性,比如name,所有这些都是在速记语法中。对不起,我没有首先正确地理解您的意思。更新了答案。
const {
header,
footer,
name,
body: {...name}, //name is not available here, but this.props.name is
//also `body: {...name}` is the same as `body: name`
title,
} = this.props;