如何将包含 props 的对象传递给 React 组件?

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

具有道具 ab 的组件可以使用以下方式呈现:

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

可以传递一个包含道具作为键的对象吗?

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

如果是,怎么做?

当然可以。确保使用 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.

你可以对这种情况使用这种扩展语法,因为你是"spreading the props to the component"。它像这样应用,但要谨慎使用:

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

以上等于单独传递道具:

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