做法:
(1)将要显示的内容作为插槽传入组件
(2)使用React.Children.map遍历插槽内容的标签属性获取标题栏内容
xx.props.键名
(3)使用React.Children.map遍历插槽内容获取要显示的元素
xx.props.children
标题栏选中高亮
自定义当前索引,设置点击事件,当当前索引等于元素索引时,添加相应类名
选中标题栏显示对应内容
在标题栏点击事件中,当当前索引等于元素索引时,添加相应类名
小写标签可以自定义,故不报错
代码示例:
组件:
import React,{Component} from 'react'
import './style.less'
class App extends Component{
state={
currentIndex:0
}
//标题栏样式函数
check_title_index=(index)=>{
return index===this.state.currentIndex ? 'Tab_title active':'Tab_title'
}
//内容是否显示样式函数
check_item_index=(index)=>{
return index===this.state.currentIndex ? 'show':'hide'
}
//标题栏点击事件
tabHandler(index)
{
this.setState({
currentIndex:index
})
}
render()
{
return(
<div>
<div className="Tab_title_wrap">
{
React.Children.map(this.props.children, (element, index) => {
return (
<div className={this.check_title_index(index) } onClick={this.tabHandler.bind(this,index) } >
{element.props.tabname}
</div>
)
})
}
</div>
<div className="Tab_item_wrap">
{
React.Children.map(this.props.children, (element, index) => {
return (
<div className={ this.check_item_index(index) }>{element.props.children}</div>
)
})
}
</div>
</div>
)
}
}
export default App
使用:
import Tabs from '../../../../components/tabs/index'
<Tabs>
<tab tabname='标题1'>内容1</tab>
<tab tabname='标题2'>内容2</tab>
</Tabs>
样式:
.Tab_title_wrap{
display: flex;
.Tab_title{
flex: 1;
text-align: center;
font-size: 15px;
margin: 20px;
border: 2px solid #ff5555;
padding: 10px;
margin-bottom: 0;
}
}
.hide{
display: none;
}
.active{
color:red;
}
.show{
display: block;
}
效果图