在Wordpress块开发的上下文中,理解来自props的const赋值的问题



我不确定这是否是我对JavaScript、React或Wordpress对React的修改缺乏了解,但这是在做什么?

export default function MyFunction( props ) {
const {
attributes: {
foo1,
foo2
},
setAttributes,
} = props;

我认为这是在使用React道具并创建两个范围为MyFunctionconst:";属性";以及";setAttributes";。但是,稍后,如果我做一些类似的事情

return (
<>
<Fragment>
<div>{ foo1 }</div> // this works fine
<div>{ attributes }</div> // this says "ReferenceError: Can't find variable: attributes"
</Fragment>
</>
);

我不明白为什么我可以引用foo1而不去attributes.foo1;我不明白为什么我不能引用属性。所以,我显然不明白什么是";简单的";分配帮助

在进行对象排列时,您已经钻取了attributes,因此只分配了内部值。有几种方法可以解决这个

export default function MyFunction( props ) {
const {
attributes: {
foo1,
foo2
},
attributes, // grab attributes too
setAttributes,
} = props;
export default function MyFunction( props ) {
const {
attributes,
setAttributes,
} = props;
const { foo1, foo2 } = attributes; // grab the values after

或者,您可以简单地获取如上所述的属性,并使用点符号attributes.foo1

最新更新