react使用hook封装一个tab组件
Tabbar.jsx
import PropsTypes from "prop-types";
import React, { useEffect, useState } from 'react';
export default function Tabbar(props) {
const { tabData , current } = props
const [currentTab,setCurrentTab] = useState('test')
const tabchange = (item) => {
setCurrentTab(item.key)
}
useEffect(()=>{
setCurrentTab(current)
},[current])
return (
<div style={{display: 'flex',justifyContent: 'space-around',alignItems: 'center'}}>
{
tabData.map(item=>{
return (
<div
style={{
flex:'1',textAlign:'center',marginRight:'5px',cursor:'pointer',
color: item.key === currentTab ? 'red' : '#000',
background: item.key === currentTab ? '#ccc' : '#eee',
}}
key={item.key}
onClick={ () => tabchange(item) }
>
{ item.name }
</div>
)
})
}
</div>
)
}
Tabbar.propTypes = {
current: PropsTypes.oneOfType([PropsTypes.string, PropsTypes.number]),
tabData: PropsTypes.array.isRequired
};
Tabbar.defaultProps = {
tabData: [
{
name:'测试1',
key:'test1'
},
{
name:'测试2',
key:'test2'
},
],
current:''
};
使用组件
import React from 'react';
import Tabbar from "../tabbar/Tabbar";
export default function App(props) {
const tabData = [
{
name:'篮球',
key:'1'
},
{
name:'足球',
key:'2'
},
{
name:'排球',
key:'3'
}
]
const current = '2'
return (
<div className='content'>
<Tabbar tabData={tabData} current={current} ></Tabbar>
<div style={{marginBottom: '10px'}}></div>
<Tabbar></Tabbar>
</div>
)
}
效果