import * as React from 'react' import * as Styled from './index.style' interface Props { tabList?: string[]; onChange?: (index: number) => void; } class Tab extends React.Component { state = { active: 0, scrollData: [] } refList: any = [] containerRef: any = null handleTabClick = (index: number) => { const { scrollData } = this.state this.setState({ active: index }) this.props.onChange?.(index) this.containerRef.scroll({ left: scrollData[index - 1] - 45 || 0, behavior: 'smooth' }) } calcTabWidth = () => { const { scrollData } = this.state let newScrollData = scrollData.slice() this.refList.forEach((item, index) => { let width = item?.getBoundingClientRect().width if (index > 0) { newScrollData[index] = width + newScrollData[index - 1] } else { newScrollData[index] = width } }) this.setState({ scrollData: newScrollData }) } componentDidUpdate(preProps) { if (this.props.tabList !== preProps.tabList) { this.calcTabWidth() } } public render() { const { tabList } = this.props const { active } = this.state return ( this.containerRef = ref} > { tabList?.map((tab, index) => ( this.refList[index] = ref} active={active === index} onClick={this.handleTabClick.bind(this, index)} > {tab} )) } ) } } export default React.memo(Tab)