index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import React, { Component } from 'react';
  2. import './index.less';
  3. import Assets from '@src/components/Assets';
  4. function getKey(type, index, selected, answer) {
  5. return `${(selected[type] || [])[index] ? 'selected' : ''} ${(answer[type] || [])[index] ? 'true' : 'false'}`;
  6. }
  7. export default class AnswerSelect extends Component {
  8. constructor(props) {
  9. super(props);
  10. const select = [];
  11. for (let i = 0; i < props.list.length; i += 1) {
  12. select[i] = false;
  13. }
  14. let index = -1;
  15. const { selected = {}, answer = {}, type } = props;
  16. let result = true;
  17. (selected[type] || []).forEach((row, i) => {
  18. if (row) index = i;
  19. if (row !== answer[type][i]) result = false;
  20. });
  21. if (index === -1) {
  22. (answer[type] || []).forEach((row, i) => {
  23. if (row) index = i;
  24. });
  25. }
  26. this.state = { selecting: false, select, index, result };
  27. }
  28. onChange(index) {
  29. const { onChange } = this.props;
  30. const { select } = this.state;
  31. for (let i = 0; i < select.length; i += 1) {
  32. select[i] = false;
  33. }
  34. select[index] = true;
  35. if (onChange) onChange(select);
  36. this.close();
  37. this.setState({ index });
  38. }
  39. open() {
  40. this.setState({ selecting: true });
  41. }
  42. close() {
  43. this.setState({ selecting: false });
  44. }
  45. render() {
  46. const { selecting, index, result } = this.state;
  47. const { list = [], show, selected = {}, answer = {}, type, fix } = this.props;
  48. const title = list.length > 0 && index >= 0 ? list[index] : ' ';
  49. return (
  50. <div className="answer-select">
  51. <div hidden={!selecting} className="mask" onClick={() => this.close()} />
  52. <div className={`select-warp ${show ? (result ? 'true' : 'false') : ''}`}>
  53. <div className="text" onClick={() => this.open()}>
  54. {` ${title}`}
  55. <Assets name="chooser_icon" />
  56. </div>
  57. <div className={`select-body ${selecting ? 'select' : ''}`}>
  58. {list.map((item, i) => {
  59. return (
  60. <div className={`item ${getKey(type, i, selected, answer)} ${show ? 'show' : ''}`} onClick={() => !fix && this.onChange(i)}>
  61. <div className="icon" />{item}
  62. </div>
  63. );
  64. })}
  65. </div>
  66. </div>
  67. </div>
  68. );
  69. }
  70. }