正如其他人說,它沒有任何意義的按鈕是你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