reactjs 将对象作为道具传递给 jsx
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49081549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing object as props to jsx
提问by Sabrina
I have an object contains multiple common key-value props, that I want to pass on to some jsx. Something like this:
我有一个对象包含多个常见的键值道具,我想传递给一些 jsx。像这样的东西:
const commonProps = {myProp1: 'prop1',myProp2: 'prop2'};
<MyJsx commonProps />
I want this to function as passing individual props:
我希望它起到传递单个道具的作用:
<MyJsx myProp1={commonProps.myProp1} myProp2={commonProps.myProp2}/>
Is this possible?
这可能吗?
回答by Mayank Shukla
Is this possible?
这可能吗?
Yes, why you think its not possible, but the way you are sending is not correct.
是的,为什么您认为这是不可能的,但是您发送的方式不正确。
Meaning of <MyJsx commonProps />is:
的意思<MyJsx commonProps />是:
<MyJsx commonProps={true} />
So if you don't specify any value by default it will take true. To pass the object you need to write it like this:
因此,如果默认情况下您不指定任何值,它将采用true. 要传递对象,您需要像这样编写它:
const commonProps = {myProp1: 'prop1',myProp2: 'prop2'};
<MyJsx commonProps={commonProps} />
Update:
更新:
If you have an object and wants to pass all the properties as separate prop, write it like this:
如果您有一个对象并希望将所有属性作为单独的 prop 传递,请像这样编写:
<MyJsx {...commonProps} />
回答by G_S
You can use the spread operatorto do this.
您可以使用扩展运算符来执行此操作。
You can simply do <MyJsx {...commonProps} />
你可以简单地做 <MyJsx {...commonProps} />
Now what all individual properties you have in commonProps will be sent as individual props to MyJsx.
现在,您在 commonProps 中拥有的所有单独属性将作为单独的 props 发送到 MyJsx。
回答by sharp
You need to use double braces, like this:
您需要使用双大括号,如下所示:
messages={{tile:'Message 1'}}
Or to pass many objects:
或者传递许多对象:
messages={[{title:'Message 1', name: 'Andrew'}, {title:'Message 2', name: 'Greg'}]}
It's simply JS syntax inside braces.
它只是大括号内的 JS 语法。
A final component might look like this
最终组件可能如下所示
<Chat title="Some str" messages={[{title:'Message 1', name: 'Andrew'}, {title:'Message 2', name: 'Greg'}]} />
回答by sneha
You can pass props as object in two ways:-
您可以通过两种方式将道具作为对象传递:-
const commonProps = {myProp1: 'prop1',myProp2: 'prop2'};
const commonProps = {myProp1: 'prop1',myProp2: 'prop2'};
1.Using spread Operator:-
1.使用传播运算符:-
<MyJsx {...commonProps} />
2.Simply pass that props:-
2.简单地传递那个道具:-
<MyJsx commonProps = {commonProps ? commonProps : true} />

