[英]Dynamically add a prop to a ReactJS object
I have this object created as follows 我有如下创建的对象
let comp = <MyComponent
msg="hello"
>
Now I want to add another property foo="bar" to object comp. 现在,我想向对象comp添加另一个属性foo =“ bar”。 I could always have something like 我总会喜欢
let comp = <MyComponent
msg="hello"
foo={this.state.barOrNoBar}
>
But I am getting an array of these objects from another piece of code and cannot add foo there. 但是我从另一段代码中获取了这些对象的数组,并且无法在其中添加foo。 I just want to add this property only as needed. 我只想根据需要添加此属性。 What is the right way to do this (other than doing a DOM findNode and using setAttribute)? 什么是正确的方法(除了执行DOM findNode和使用setAttribute之外)?
You can create a functional component like this: 您可以这样创建一个功能组件:
const MyComp = ({barOrNone = null}) =>
<MyComponent msg="hello" foo={barOrNone} />;
And then, to use it: 然后,使用它:
<MyComp barOrNone={this.state.barOrNone} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.