正如其他人说,它没有任何意义的按钮是你Tabs
组件外。
我看到您的代码示例的方式,您的App
组件应该是您的Tabs
组件,并且我假设您的Tabs
组件代表某种TabsView
。
app.js
import Tabs from './components/tabs';
<App>
<Tabs/>
</App>
tabs.js
class TabsView extends Component {
constructor(props){
super(props);
}
render(){
return(
<span>{this.props.currentTab}</span>
);
}
}
class Tabs extends Component {
constructor(props){
super(props);
this.state = {
currentTab: 0
}
}
handleOnClickPrev(){
this.setState({currentTab: currentTab--});
}
handleOnClickNext(){
this.setState({currentTab: currentTab++});
}
render(){
return(
<div>
<TabsView currentTab={this.state.currentTab}/>
<button id="prev" onClick={handleOnClickPrev.bind(this)}>-</button>
<button id="next" onClick={handleOnClickNext.bind(this)}>+</button>
</div>
);
}
}
export default Tabs;
这样你的组件的所有功能,生活在其中。 Tabs
组件现在拥有它所需的所有信息。您使用的每个Tabs
组件都将具有其自己的状态和选项卡。如果你想让你的currentTab状态来自App
,这样你可以在其他地方渲染这个相同的currentTab,你可以通过你的App
组件作为道具传递它。
app.js
<App>
<Tabs currentTab={this.state.currentTab} handlePrev={} handleNext={}/>
</App>
tabs.js
class Tabs extends Component {
constructor(props){
super(props);
}
render(){
return(
<div>
<TabsView currentTab={this.props.currentTab}/>
<button id="prev" onClick={this.props.handlePrev}>-</button>
<button id="next" onClick={this.props.handleNext}>+</button>
</div>
);
}
}
export default Tabs;
如果你希望显示在某些地方标签和在其他地方的按钮,你可以使用TabsView
组件使用您传递给Tabs
组件的相同道具。
app.js
<App>
<Tabs currentTab={this.state.currentTab} handlePrev={} handleNext={}/>
<TabsView currentTab={this.state.currentTab} />
</App>
如果你在具有对生活在不同的地方比组件本身的组件的控制真的背水战,我会建议通过同样的道具到两个TabsView
和纽扣。
app.js
handlePrev() {
this.setState({ currentTab: this.state.currentTab - 1 })
}
handleNext(){
...
}
render(){
return (
<App>
<TabsView currentTab={this.state.currentTab} />
<button id="prev" onClick={this.handlePrev.bind(this)}>-</button>
<button id="next" onClick={this.handleNext.bind(this)}>+</button>
</App>
)
}
我不认为这是有道理的,你引进终极版或在这一点上任何其他国家图书馆。仅仅为你的标签组件管理全局状态是矫枉过正的。
太棒了。经过一番思考后,这种方法更具“反应性”。谢谢!我结束了这个解决方案。 <3 – Richard