简体   繁体   中英

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:

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.

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. It then returns the 1st argument.

What data structure are you passing to this arrow function? Objects in javascript require : 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) => <Entity {...params} />)({ a: "val", b: "val", c: "val"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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