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>
)
}
效果
文章来源地址https://www.toymoban.com/news/detail-700390.html
文章来源:https://www.toymoban.com/news/detail-700390.html
到了这里,关于react使用hook封装一个tab组件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!