简体   繁体   English

如何使用默认值将无状态组件中的道具(反应)转换为变量,并在JSX中使用该变量应用扩展运算符?

[英]How to destructure props in stateless component (react) with default values into a variable and apply spread operator with that variable in JSX?

The code below renders correctly 下面的代码正确呈现

export default ({
  primitive = "a-sky",
  height = "2048",
  radius= "30",
  width= "2048"
}) => {
const properties = { primitive, height, radius, width}
return <Entity {...properties} />
}

However, is there something I can do to omit the need for duplicating the prop names primitive, height, etc ? 但是,我能做些什么来省略复制道具名称原语,高度等的需要吗?

The code below does not work but shows what I mean to accomplish 下面的代码不起作用,但显示了我的意思

let properties
export default ({
  primitive = "a-sky",
  height = "2048",
  radius= "30",
  width= "2048"
} = properties) => {
return <Entity {...properties} />

} }

What you're trying to do is clever, but object destructuring doesn't allow you to strip properties while placing them in another object. 你想要做的是聪明,但是对象解构不允许你在将属性放入另一个对象时去除属性。 However, you can spread the props into an object that you put defaults on, and return that object: 但是,您可以将props展开到您放置默认值的对象中,并返回该对象:

export default props => {
  const propsWithDefaults = {
    primitive: "a-sky",
    height: "2048",
    radius: "30",
    width: "2048",
    ...props
  };

  return <Entity {...propsWithDefaults} />
}

The properties in props will override the properties you hardcode in. props的属性将覆盖您硬编码的属性。

Edit: Another way which seems to be more of what you're looking for: 编辑:另一种看起来更像你正在寻找的方式:

export default props => {
  const defaultProps = {
    primitive: "a-sky",
    height: "2048",
    radius: "30",
    width: "2048"
  };

  return <Entity {...Object.assign(defaultProps, props)} />
}

Object.assign takes the first argument, and puts all properties of subsequent arguments on that first argument, overriding conflicts as it goes left to right. Object.assign接受第一个参数,并将后续参数的所有属性放在第一个参数上,从左到右覆盖冲突。 It then returns the 1st argument. 然后它返回第一个参数。

What data structure are you passing to this arrow function? 您传递给此箭头函数的数据结构是什么? Objects in javascript require : not = . javascript中的对象需要: not = If you're trying to declare default values such as the following notation: 如果您尝试声明默认值,例如以下表示法:

( x = 'default for x', y = 'default for y' ) => {
    console.log(x, y);
}

Then remove the { } from within the parameter portion of the arrow function. 然后从箭头函数的参数部分中删除{ }

Bringing it back to what you've posted though: 把它带回你发布的内容:

I'd recommend passing your arrow function a single object called params then use the spread operator on that. 我建议将箭头函数传递给一个名为params对象,然后在其上使用spread运算符。

((params) => <Entity {...params} />)({ a: "val", b: "val", c: "val"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM