其實,在我們日常的編程當中,經常會碰到tab切換的模塊,那么,實現他的方法也有很多中,下面是一款簡單,容易理解的react tab切換方法。

通過設置state中的current 屬性去控制tab 和 內容模塊。
this.state = {
current: 0,
cities:['香港','北京','上海','台北'],
content:[{
number: '13866666666',
email: '111@qq.com,
time: 'test123',
},{
number: '13877777777',
email: '222@qq.com',
time: 'test456',
},{
number: '13888888888',
email: '333@qq.com',
time: 'test789',
},{
number: '13899999999',
email: '444@qq.com',
time: 'test000',
}]
};
定義一個tab onClick 事件的方法 itemNav,並接收當前點擊的index索引號,賦值給current
itemNav = (index) =>{
this.setState({
current: index,
})
}
循環出tab 標簽 並添加點擊改變index索引事件,添加onClick執行itemNav方法,傳入當前點擊的索引號
<TabContent>
{this.state.cities.map((item,index) =>{
return (
<span key={index} className={ index === this.state.current ? 'state-active' : ''} onClick={ () => { this.itemNav(index)} }>{item}</span>
);
})}
</TabContent>
循環出內容模塊,通過index索引號改變需要顯示模塊
<ContentContainer>
{this.state.content.map((item,index) =>{
return (
<ul key={index} className={index === this.state.current ? 'state-active' : ''} >
<li>
<p>測試標題</p>
</li>
<li>
<p>
<TelPhone fontSize="14px" color="#687593" />
<span>{item.number}</span>
</p>
</li>
<li>
<p>
<Email fontSize="14px" color="#687593" />
<a href={`mailto:${item.email}`}>{item.email}</a>
</p>
</li>
<li>
<p><span>{item.time}</span></p>
</li>
</ul>
);
})}
</ContentContainer>
這樣,一個簡單的react tab 切換就搞定了... css樣式需要您添加自己需要的樣式...(不喜勿噴,希望這個簡單的tab切換能幫助到您)
