动态设置组件的道具 [英] Set component's props dynamically
本文介绍了动态设置组件的道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在将组件的属性存储到变量中之后,我需要设置其属性,这是伪代码:
I need to set component's props after it is stored in a variable, here is pseudo code:
render(){
let items = [{title:'hello'}, {title:'world'}];
let component = false;
switch (id) {
case 1:
component = <A />
break;
case 2:
component = <B />
break;
}
return(
items.map((item, index)=>{
return(
<span>
{/* SOMETHING LIKE THIS WOULD BE COOL - IS THAT EVEN POSSIBLE*/}
{component.props.set('title', item.title)}
</span>11
)
})
)
}
在return
内部,我运行一个循环,需要为存储在变量内的组件设置道具....如何为之前存储在变量中的该组件设置道具?
Inside return
I run a loop where I need to set props for the component that is stored inside a variable.... How to set props for this component which I stored earlier in a variable?
推荐答案
The proper way is to use React's cloneElement method (https://facebook.github.io/react/docs/react-api.html#cloneelement). You can achieve what you want by doing:
<span>
{
React.cloneElement(
component,
{title: item.title}
)
}
</span>
这篇关于动态设置组件的道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文