react寫一個select組件

以前一直用的antd的Select組件,但在有些端並不適用,而原生的select樣式修改不靈活,遂產生本身寫一個組件的想法。觀察select組件:node

<select onChange={(value) => {this.value=value}}
    <option value='1'>man</option>
    <option value='0'>woman</option>
</select>

能夠看出數據都是在option中,有值value和顯示出來的數據一一對應。若是咱們寫一個select組件,那麼應該有onChange方法,應該要訪問到子元素,並且div是沒有value這個屬性的,因此option應該也是一個組件,有value屬性。下面是我寫的組件的用法:react

import {MobileSelect, MobileOption} from '../../components/MobileSelect';

  <MobileSelect
    disabled={isDisabled}
    value={data.clarity || ringResponse.clarity || 'Flawless'}
    style={{ width: '132px' }}
    onChange={(v) => this.changeDataValue('clarity', v)}
  >
    {
      (clarity || []).map((item, i) => {
        return (
          <MobileOption key={i + ''} value={item.code}>{item.title}</MobileOption>
        );
      })
    }
  </MobileSelect>

能夠看出其和通常的select組件用法差很少。效果以下:antd

clipboard.png

下面是組件less

import {observable} from 'mobx';
import {observer} from 'mobx-react';
import React from 'react';
import {Icon} from 'antd';
import './index.less';

interface IProps {
  disabled?: boolean;
  onChange?: (value) => void;
  value?: string | number;
  style?: React.CSSProperties;
  className?: string;
}
@observer
export class MobileSelect extends React.Component<IProps> {
  @observable showOption = false;     // 是否彈出下拉框
  @observable value: any = '';        // 當前選中的value值
  @observable text: any = '';         // 選中的value值對應的文本
  @observable cell: any;              // 組件的dom節點
  componentDidMount(): void {
    // 獲取選擇框的ref,當在組件外點擊時的時候收起下拉框
    document.addEventListener('click', (e) => {
      if (this.cell && this.cell !== e.target && !this.cell.contains(e.target)) {
        this.showOption = false;
      }
    }, true);
  }
  componentWillReceiveProps(nextProps: Readonly<IProps>, nextContext: any): void {
    // 根據傳入的value值,遍歷children,找到對應值的展現文本
    if (nextProps.value !== this.props.value || nextProps.children !== this.props.children) {
      React.Children.map(this.props.children, (child, index) => {
        if (nextProps.value === child.props.value) {
          this.text = child.props.children;
        }
      });
    }
  }
  render(): React.ReactNode {
    const {children, value} = this.props;
    console.log(value);
    return (
      <div
        className={'Mobile-Select ' + this.props.className}
        style={this.props.style}
        ref={(node) => this.cell = node}
      >
        <div
          className={'select-wrap'}
          onClick={() => {
            // 禁用不能彈出下拉框
            if (!this.props.disabled) {
              this.showOption = !this.showOption;
            }
          }}
        >
          <Icon type='down' style={this.showOption ? {transform: 'rotate(180deg)'} : {transform: 'rotate(0deg)'}} className={'select-icon'}/>
          {this.text}
        </div>
        <div className={'option-wrap'} style={this.showOption ? {position: 'absolute'} : {display: 'none'}}>
          {
            React.Children.map(children, (child, index) => {
              // 設置選中option和未選中option的樣式
              let optionClassName = '';
              if (this.props.value === child.props.value) {
                optionClassName = child.props.className ? child.props.className + ' option-item selected' : 'option-item selected';
              } else {
                optionClassName = child.props.className + ' option-item';
              }
              return (
                <div
                  onClick={() => {          // 爲了在父組件給子組件添加onClick事件,包裹了一層div
                    // 有無onChange事件都能改變值
                    if (this.props.value && this.props.onChange) {
                      this.props.onChange(child.props.value);
                    } else {
                      this.text = child.props.children;
                      this.value = child.props.value;
                    }
                    console.log(this.value);
                    this.showOption = !this.showOption;
                  }}
                  style={this.props.style}
                  className={optionClassName}
                >{child}</div>
              );
            })
          }
        </div>
      </div>
    );
  }
}
interface OptionProps {
  value?: string | number;
  className?: string;
  style?: React.CSSProperties;
}
export class MobileOption extends React.Component<OptionProps> {
  render(): React.ReactNode {
    const {children} = this.props;
    return (
      <div style={this.props.style}>
        {children}
      </div>
    );
  }
}

下面是組件的樣式dom

.Mobile-Select {
  display: inline-block;
  min-width: 100px;
  margin: 0 6px;
  .select-wrap {
    border: 1px solid #e0c0a2;
    border-radius: 4px;
    padding: 5px 11px;
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;
    align-items: center;
    .select-icon {
      transition: .3s;
      float: right;
    }
  }
  .option-wrap {
    box-shadow: 0 0 5px #333;
    z-index: 1000;
    border-radius: 5px;
    .option-item {
      background-color: #fff;
      padding: 2px 11px;
      min-width: 100px;
      &.selected {
        background-color: #fbe6d0;
      }
    }
  }
}

總的來講只實現了select的基本功能。有改進的地方請指點一二。flex

相關文章
相關標籤/搜索