import React, { Component } from 'react'; import './index.less'; import RadioItem from '../RadioItem'; export default class Answer extends Component { constructor(props) { super(props); const single = []; const double = []; switch (props.type) { case 'single': for (let i = 0; i < props.list.length; i += 1) { single.push(false); } break; case 'double': for (let i = 0; i < props.list.length; i += 1) { double.push([false, false]); } break; default: break; } this.state = { single, double }; } onChangeSingle(index) { const { single } = this.state; for (let i = 0; i < single.length; i += 1) { single[i] = false; } single[index] = true; this.setState({ single }); this.onChange(single); } onChangeDouble(index, column) { const { direction } = this.props; let { double } = this.state; switch (direction) { case 'landscape': double[index] = double[index].map(() => false); break; case 'portrait': double = double.map(row => { row[index] = false; return row; }); break; default: break; } double[index][column] = true; this.setState({ double }); this.onChange(double); } onChange(value) { const { onChange } = this.props; if (onChange) onChange(value); } render() { return <div className="answer">{this.renderDetail()}</div>; } renderDetail() { const { type } = this.props; switch (type) { case 'single': return this.renderList(); case 'double': return this.renderTable(); default: return <div />; } } renderList() { const { list = [] } = this.props; const { single = [] } = this.state; return ( <div className="list"> {list.map((item, index) => { return ( <div className="item"> <RadioItem checked={single[index]} onClick={() => this.onChangeSingle(index)} /> <div className="text">{item}</div> </div> ); })} </div> ); } renderTable() { const { list = [] } = this.props; const { double = [] } = this.state; return ( <table border="1" bordercolor="#d8d8d8"> <thead> <tr className="bg"> <th align="center" width="100" className="t-c"> Both acce </th> <th align="center" width="100" className="t-c"> Otherwise </th> <th /> </tr> </thead> <tbody> {list.map((item, index) => { return ( <tr> <td align="center" className="bg"> <RadioItem checked={double[index][0]} onClick={() => this.onChangeDouble(index, 0)} /> </td> <td align="center" className="bg"> <RadioItem checked={double[index][1]} onClick={() => this.onChangeDouble(index, 1)} /> </td> <td>{item}</td> </tr> ); })} </tbody> </table> ); } }