【发布时间】:2018-12-21 08:06:28
【问题描述】:
我有一个Parent(带有三个按钮的蓝色框)和一个Child(显示内容的红色框)组件,它们根据Child 的状态呈现一些文本。基本上,渲染的视图是这样的:
Child 组件:
class Child extends Component {
constructor(props) {
super(props);
this.state = {
tab: this.props.tab
}
}
render() {
let text;
if (this.props.tab === '1') {
text = <div>text 1 </div>
} else if (this.props.tab === '2') {
text = <div>text 2 </div>
} else if (this.props.tab === '3') {
text = <div>text 3 </div>
}
return (
<div>
{text}
</div>
);
}
}
export default Child;
Parent 组件:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
tab: null
}
this.onOneClik = this.onOneClik.bind(this);
this.onTwoClik = this.onTwoClik.bind(this);
this.onThreeClick = this.onThreeClick.bind(this);
}
onOneClik(e) {
this.setState({ tab: '1' });
}
onTwoClik(e) {
this.setState({ tab: '2' });
}
onThreeClick(e) {
this.setState({ tab: '3' });
}
render() {
return (
<div>
<button type="button" onClick={this.onOneClik}>1</button>
<button type="button" onClick={this.onTwoClik}>2</button>
<button type="button" onClick={this.onThreeClik}>3</button>
</div>
<div>
<Child tab={this.state.tab} />
</div>
);
}
}
问题是单击按钮时我需要重新渲染子项,但子项仅显示首先单击的按钮的内容,即使单击不同按钮时父项的状态会自行更新.
在不涉及链接的情况下动态呈现子项的方法是什么?我想 redux 可能会有所帮助,但我不确定如何将 redux 包装起来。
【问题讨论】:
标签: javascript reactjs