简体   繁体   中英

How do I pass an object containing props to React component?

A component with props a and b can be rendered using:

<Component a={4} b={6} />

Can one pass an object instead that contains the props as keys, something like this?

let componentProps = { a: 4, b: 6 }
<Component componentProps />

If so, how?

Sure. Make sure to use spread syntax . Per the React documentation :

Spread Attributes

If you already have props as an object, and you want to pass it in JSX, you can use ... as a "spread" operator to pass the whole props object. These two components are equivalent:

 function App1() { return <Greeting firstName="Ben" lastName="Hector" />; } function App2() { const props = {firstName: 'Ben', lastName: 'Hector'}; return <Greeting {...props} />; } 

Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.

You can use this spread syntax to this situation, because you're "spreading the props to the component". It's applied like so, though use this sparingly:

let componentProps = { a: 4, b: 6 }
<Component {...componentProps} />

The above is equal to passing the props separately:

<Component a={4} b={6} />

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