替换更简单和更短的方式比switch - reactjs
问题描述:
当我知道在变量是字符串'numpad',我怎么可以简单渲染组件具有相同的名称?我有组件Numpad,UnitList,ShiftList,我想单独渲染它们。我在我的孩子回调,并且我发回组件类型(字符串),我想要从我的父母呈现。然后我将我的变量设置为numpad,unitList或shiftList,然后我想呈现此组件。有没有更简单的方法,比写开关?随着开关我可以 -替换更简单和更短的方式比switch - reactjs
switch(type){
case 'numpad':
<Numpad .../>
break;
case 'unitList':
.....
}
但我在寻找更简单和更短的东西。
现在我有 -
render(){
return(
<div>
<Child update={this.renderSomeComponent.bind(this)} />
{(() => {
switch (this.state.type) {
case "numpad": return <Numpad ../>;
case "unitList": return <UnitList ../>;
case "shiftList": return <ShiftList ../>;
case "sideList": return <SideList ../>;
default: return false;
}
})()}
</div>
)
}
renderSomeComponent(type){
this.setState({
type: type
})
}
在孩子的分量,我有方法 -
handleClick(){
this.props.update(this.props.type);
}
答
一般来说,当你想避免switch ... case
,您可以使用JavaScript对象来处理映射。在你的榜样,这意味着创建一个对象,它的键是你的变量的不同值和值预期输出:
const map = {
value1: output1,
value2: output2,
...
}
你上面给然后可以写如下的代码:
import React from "react";
import Numpad from "the-location-of-your-numpad-component";
import UnitList from "the-location-of-your-unitList-component";
...
const mapTypeToComponent = {
numpad: Numpad,
unitList: UnitList,
...
}
// In your component
render(){
const { type } = this.state;
const ComponentToShow = mapTypeToComponent[type];
return(
<div>
<Child update={this.renderSomeComponent.bind(this)} />
<ComponentToShow />
</div>
)
}
希望这可以帮助
我想你应该分享更多关于你想做什么的代码。这并不明确。 – cdagli
好的,等一下:D –
你在哪里设置'this.state.type'?在孩子中,你如何使用'rednerSomeComponent'? –