变化4
数据格式
const tabs = [ { key: '', value: '全部' }, { key: '1', value: '已审核' }, { key: '2', value: '未审核' }, ];
父组件
<GeYao tabs={tabs} onTabSearch={this.handleTabChange} />
子组件
import React, { Component } from 'react'; class GeYao extends React.Component { constructor(props) { super(props); this.state = { selectTab: props.selectTab || '', mouseOverTable: '', }; } /** * 切换tab * @param {Boolean} doNot 是否不做任何事情,如果存在此值,不执行父组件切换方法,仅仅刷新样式 */ handleTabClick(key, doNot) { console.log(key, 'key'); this.setState({ selectTab: key, }); if (!doNot) { try { this.props.onTabSearch(key); } catch (error) {} } } render() { const { selectTab, mouseOverTable } = this.state; const { tabs = [], styles, itemStyles } = this.props; return ( <ul style={{ display: 'flex', background: '#FFFFFF', paddingLeft: '32px', width: '100%', ...styles, }} > {tabs.map((item, index) => { const marginStyle = index === 0 ? { marginLeft: 0, } : {}; return ( <li onMouseOver={() => this.setState({ mouseOverTable: item.key })} onMouseLeave={() => this.setState({ mouseOverTable: 'mouseLeave' })} onClick={() => this.handleTabClick(item.key)} style={{ color: item.key === selectTab || item.key === mouseOverTable ? '#1890FF' : '#000000A6', borderBottom: item.key === selectTab ? '2px solid #1890FF' : '', padding: '0px 1.5% 8px', cursor: 'pointer', whiteSpace: 'nowrap', ...itemStyles, ...marginStyle, }} key={item.key} > {item.name || item.value || ''} </li> ); })} </ul> ); } } export default GeYao;
运行结果
图解
总结
我是歌谣 放弃很容易 但是坚持一定很酷 谢谢你的鼓励 微信公众号前端小歌谣 加入前端巅峰交