[英]How pass the same props to every child in Component
我有一個呈現條件不同組件的組件。 我不能在每個地方傳遞相同的道具,因為這會破壞漂亮的代碼。 我該如何優化呢?
render(){
const {what, y} = this.props.ddd
return(){
{what === "XXX" && <> <SmthComp1 x=y /> <SmthComp2 x=y /> }
{what === "ZZZ" && <> <SmthComp3 x=y /> <SmthComp34 x=y /> }
{what === "YYY" && <> <SmthComp5 x=y /> <SmthComp12 x=y /> }
{what === "BBB" && <> <SmthComp6 x=y /> <SmthComp23 x=y /> }
{what === "GGG" && <> <SmthComp7 x=y /> <SmthComp21 x=y /> }
}
}
實際上,還有更多的道具(不僅是x),這破壞了代碼。 但是它們總是一樣的。
每個組件的prop x的值為y。 我不想將此傳遞給每個組件。
您可以將props保存到var中,然后將它們傳播到組件上:
render(){
const {what, y} = this.props.ddd
const props = {x: y}
return(){
{what === "XXX" && <> <SmthComp1 {...props} /> <SmthComp2 {...props} /> }
//...
}
}
您可以使用組件圖並將道具存儲在變量中,如下所示:
render() {
const {what, y} = this.props.ddd
const componentsMap = {
"XXX" : [SmthComp1, SmthComp2],
"ZZZ" : [SmthComp3, SmthComp34],
"YYY" : [SmthComp5, SmthComp12],
"BBB" : [SmthComp6, SmthComp23],
"GGG" : [SmthComp7, SmthComp21],
};
const componentProps = { x: y };
return() {
<>
{componentsMap[what].map(Component => <Component {...componentProps} />)}
</>
}
}
您可以將componentsMap
放置在render方法之外,因為它不會改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.