如何将 prop 从 React 中的组件数组传递给组件
How to pass prop to component from array of components in React
假设您有一个组件数组:
var my_array = [ <SomeComponent1 textcolor={defaultFontColor} />, <MyComponent2 textcolor={defaultFontColor} />}, <SomeComponent3 textcolor={defaultFontColor} />}, ...]
并且您想遍历数组,但也将 props 传递给组件(在示例中,AComponent
):
my_array.map(AComponent => {
return (
<View>
{AComponent}
</View>
)
})
在此示例中,我如何将道具传递给 {AComponent}
?
将组件视为一个 json 对象
AComponent = {
props:{
prop1: "value for the prop1"
}
}
所以,现在你可以传递你想要的道具了
my_array.map(AComponent => {
AComponent.props["newProp"] = "propValue"
return (
<View>
{AComponent}
</View>
)
})
或者,如果你想使用在数组中推送组件时传递的道具,你可以直接在组件的 render() 方法中使用它们
假设您有一个组件数组:
var my_array = [ <SomeComponent1 textcolor={defaultFontColor} />, <MyComponent2 textcolor={defaultFontColor} />}, <SomeComponent3 textcolor={defaultFontColor} />}, ...]
并且您想遍历数组,但也将 props 传递给组件(在示例中,AComponent
):
my_array.map(AComponent => {
return (
<View>
{AComponent}
</View>
)
})
在此示例中,我如何将道具传递给 {AComponent}
?
将组件视为一个 json 对象
AComponent = {
props:{
prop1: "value for the prop1"
}
}
所以,现在你可以传递你想要的道具了
my_array.map(AComponent => {
AComponent.props["newProp"] = "propValue"
return (
<View>
{AComponent}
</View>
)
})
或者,如果你想使用在数组中推送组件时传递的道具,你可以直接在组件的 render() 方法中使用它们