import * as Nerv from 'nervjs' import classnames from 'classnames' export interface SwitchProps { className?: string, type?: string, value?: any, size?: string, disabled?: any } class Switch extends Nerv.Component { private value: boolean private checkedText: any private unCheckedText: any constructor (props) { super(props) this.value = props.value == 'true' ? true : false this.state = { switchClass: this.value ? 'at-switch--checked' : '' } this.onClick = this.onClick.bind(this) } onClick (e: any) { if (this.props.disabled) { return } if (this.value) { this.setState({ switchClass: '' }) this.value = false } else { this.setState({ switchClass: 'at-switch--checked' }) this.value = true } if (this.props.onClick) {this.props.onClick(e, this.value)} if (this.props.onChange) {this.props.onChange(e, this.value)} } renderButtonClassNames (props: SwitchProps) { return classnames('at-switch', [ this.state.switchClass, props.disabled ? 'at-switch--disabled' : '', props.size ? `at-switch--${props.size}` : '' ], props.className) } render () { const switchClass = this.renderButtonClassNames(this.props) return ( {this.value ? this.checkedText : this.unCheckedText} ) } componentWillReceiveProps (props) { Nerv.Children.forEach(props.children as any, (child) => { const childOfChild = child.children if (child.props.slot === 'checkedText') { if (childOfChild.vtype != 1) { this.checkedText = child.children } else { this.checkedText = {childOfChild.text} } } else if (child.props.slot === 'unCheckedText') { if (childOfChild.vtype != 1) { this.unCheckedText = child.children } else { this.unCheckedText = {childOfChild.text} } } }, null) } } export default Switch