gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:34:06 24 4
gpt4 key购买 nike

带有 props ab 的组件可以使用以下方式渲染:

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

可以传递一个包含 props 作为键的对象,就像这样吗?

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

如果是这样,怎么办?

最佳答案

当然。确保使用 spread syntax 。每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.

您可以在这种情况下使用这种扩展语法,因为您正在“将 props 扩展到组件”。它的应用方式如下,但请谨慎使用:

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

上面相当于单独传递props:

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

关于reactjs - 如何将包含 props 的对象传递给 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44192957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com