index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import React, { Component } from 'react';
  2. import './index.less';
  3. import Button from '../Button';
  4. export default class Select extends Component {
  5. constructor(props) {
  6. super(props);
  7. this.state = { selecting: false };
  8. }
  9. componentWillMount() { }
  10. componentWillUnmount() { }
  11. open() {
  12. this.setState({ selecting: true });
  13. }
  14. close() {
  15. this.setState({ selecting: false });
  16. }
  17. render() {
  18. const { selecting } = this.state;
  19. const {
  20. className = '',
  21. placeholder,
  22. value,
  23. list = [],
  24. size = 'basic',
  25. theme = 'theme',
  26. excludeSelf,
  27. onChange,
  28. } = this.props;
  29. let index = -1;
  30. for (let i = 0; i < list.length; i += 1) {
  31. if (list[i].key === value) {
  32. index = i;
  33. break;
  34. }
  35. }
  36. if (!value && value !== '') {
  37. index = -1;
  38. }
  39. // 未选中,显示占位符
  40. // 无占位符,显示第一个
  41. // 没有内容,显示占位符
  42. if (index < 0 && !placeholder) {
  43. index = 0;
  44. }
  45. const title = list.length > 0 && index >= 0 ? list[index].title : placeholder;
  46. return (
  47. <div className={`select ${className} ${theme || ''} ${size}`}>
  48. <div hidden={!selecting} className="mask" onClick={() => this.close()} />
  49. <div className={`select-warp ${selecting ? 'active' : ''}`}>
  50. <Button size={size} theme={theme} radius onClick={() => this.open()}>
  51. {title} <i className={selecting ? 'up-arrow' : 'down-arrow'} />
  52. </Button>
  53. <div className={`select-body ${selecting ? 'selected' : ''}`}>
  54. {list.map((item, i) => {
  55. if (excludeSelf && index === i) return null;
  56. return (
  57. <div
  58. className="select-option"
  59. onClick={() => {
  60. if (onChange) onChange(item);
  61. this.close();
  62. }}
  63. >
  64. {item.title}
  65. </div>
  66. );
  67. })}
  68. </div>
  69. </div>
  70. </div>
  71. );
  72. }
  73. }