/// import * as React from 'react'; import classNames from 'classnames'; import Hammer from 'react-hammerjs'; import FormCore from '../form/core'; const prefix = 'tsp-component-Choice'; class Choice extends React.Component { constructor(props: TspComponentChoicelProps, state: TspComponentChoicelState) { super(props, state); this.onClick = this.onClick.bind(this); } public static defaultProps: TspComponentChoicelProps = { id: '', type: 'radio', value: [], onClick: null }; // public state: TspComponentChoicelState = { // value: [] // }; /** * FormCore 实例 */ private formCore: FormCore; public componentWillMount(): void { const length = this.props.value.length; const temp = []; let i; for (i = 0; i < length; i++) { if (this.props.type === 'radio') { if (this.props.value[i].checked) { temp[0] = this.props.value[i].id; break; } } else { temp.push(this.props.value[i].checked); } } this.setState({ value: temp }); } public componentDidMount(): void { this.formCore = new FormCore({ elem: this.refs.elem as HTMLElement, required: this.props.required, defaultValue: this.props.value.filter((value) => value.checked).map((value) => value.id).join() }); this.setElemValue(); } public componentDidUpdate(): void { this.setElemValue(); } /** * 点击事件 */ public onClick(index: number): void { if (this.props.onClick && !this.props.disabled) { this.props.onClick(index); } } public setElemValue(): void { const length = this.props.value.length; const value = []; for (let i = 0; i < length; i++) { const id = this.props.value[i].id.toString(); if (this.props.value[i].checked) { value.push(id); } } this.formCore.elem.dataset.value = value.join(); } public render(): JSX.Element { return ( {this.props.value.map((value, i) => ( this.onClick(i)} key={i}> {value.label} ))} ); } } export default Choice;