import Classnames from 'classnames' ; import * as React from 'react' ; import { SegmentedControlProps } from './interface' ; import './style' ; const { useState , useEffect } = React ; const prefixCls = 'cp-ui-segment' ; const noop = ( ) => { } ; const defaultProps = { prefixCls : prefixCls , selectedIndex : 0 , disabled : false , values : [ ] , onChange : noop , onValueChange : noop , style : { } , tintColor : '' } ; const getClassNames = ( { prefixCls , disabled , className } ) => { return Classnames ( className , prefixCls , { [ `${ prefixCls }-disabled` ] : disabled } ) ; } ; const getItemClassNames = ( { prefixCls } , selected ) => { return Classnames ( `${ prefixCls }-item` , { [ `${ prefixCls }-item-selected` ] : selected } ) ; } ; const onClick = ( props , index , value , selectedIndex , setSelectedIndex ) => { const { disabled , onChange , onValueChange } = props ; if ( ! disabled && selectedIndex !== index ) { if ( onChange ) { onChange ( index , value ) ; } if ( onValueChange ) { onValueChange ( value ) ; } setSelectedIndex ( index ) ; } } ; const renderSegmentItem = ( props , idx , value , selected , selectedIndex , setSelectedIndex ) => { const { prefixCls , disabled , tintColor } = props ; const itemStyle = { color : selected ? '#fff' : tintColor , backgroundColor : selected ? tintColor : 'transparent' , borderColor : tintColor } ; const activeInnerStyle = tintColor ? { backgroundColor : tintColor } : { } ; const itemCls = getItemClassNames ( props , selected ) ; return ( < div key = { `${ prefixCls }-item-${ idx }` } className = { itemCls } style = { itemStyle } role = "tab" aria - selected = { selected && ! disabled } aria - disabled = { disabled } onClick = { disabled ? undefined : ( ) => onClick ( props , idx , value , selectedIndex , setSelectedIndex ) } > < div className = { `${ prefixCls }-item-inner` } style = { activeInnerStyle } / > { value } < /div>); } ; const SegmentedControl = props => { const { style , values } = props ; const [ selectedIndex , setSelectedIndex ] = useState ( props . selectedIndex ) ; useEffect ( ( ) => { setSelectedIndex ( props . selectedIndex ) ; } , [ props . selectedIndex ] ) ; const classStr = getClassNames ( props ) ; return ( < div className = { classStr } style = { style } role = "tablist" > { values . map ( ( value , idx ) => renderSegmentItem ( props , idx , value , idx === selectedIndex , selectedIndex , setSelectedIndex ) ) } < /div>); } ; SegmentedControl . defaultProps = defaultProps ; export default SegmentedControl ;