在我的React应用程序中,我通过将changeView
方法作为道具从父级传递到菜单来有条件地渲染视图,具体取决于单击菜单组件中的哪个按钮。当前视图作为状态存储在父组件中。
我还想使用相同的changeView
方法来控制每个有条件渲染的视图中的按钮,使其在单击时返回菜单。
我目前正这样实现:
render() {
let view;
switch(this.state.view) {
case 0:
view = (<Menu changeView={this.changeView} />);
break;
case 1:
view = (<View changeView={this.changeView}>Test 1</View>);
break;
case 2:
view = (<View changeView={this.changeView}>Test 2</View>);
break;
default:
view = (<View changeView={this.changeView}>An error has ocurred!</View>);
}
return (
<div>
{view}
</div>
);
}
如您所见,我必须将changeView
方法分别传递给View
组件的每个实例。有什么方法可以设置View
组件,以便每个实例都可以通过changeView
道具传递,而不必每次都显式声明它?
答案 0 :(得分:3)
尝试在View组件内部移动switch语句
render() {
return (
<div>
{this.state.view === 0 && <Menu changeView={this.changeView} />}
{this.state.view > 0 && <View changeView={this.changeView}>
{() => {
switch (this.state.view) {
case 1:
return 'Test 1';
case 2:
return 'Test 2';
default:
return 'An error has ocurred!';
}
}}
</View>
</div>
);
}
答案 1 :(得分:1)
如果需要,您可以将开关更改为仅更改副本和组件。
this
答案 2 :(得分:0)
您所需要做的就是在视图内部更改文本。将文本移动到组件外部的数组,然后通过视图索引选择文本,或回退到错误:
const text = ['', 'Test 1', 'Test 2'];
class Demo extends React.Component {
state = {
view: 1
}
render() {
const { view } = this.state;
const text = text[view] || 'An error has ocurred!';
return (
<div>
{view === 0 ?
<Menu changeView={this.changeView} />
:
<View changeView={this.changeView}>{text}</View>
}
</div>
);
}
}
答案 3 :(得分:0)
您可以创建一个函数来为您执行此操作,
getView(Component, children){
return <Component changeView = {this.changeView}>{children}</Component>
}
render() {
let view;
switch(this.state.view) {
case 0:
view = getView(Menu)
break;
case 1:
view = getView(View,'Test 1')
break;
case 2:
view = getView(View,'Test 2')
break;
default:
view = getView(View,'An error has ocurred!');
}
return (
<div>
{view}
</div>
);
}