收藏

antd 异步 Select 简单封装

2017-11-21  本文已影响342人  lesliefang
import React from 'react';
import {Select} from 'antd';
import PropTypes from 'prop-types';
const Option = Select.Option;

export default class AsyncSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      value: props.value || '',
    };
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps && this.props.value !== nextProps.value) {
      this.setState({
        value: nextProps.value
      });
    }
  }

  componentDidMount() {
    if (!this.props.url) {
      return;
    }

    fetch(this.props.url)
      .then(response => response.json())
      .then(json => {
        let data = json;
        if (this.props.dataMapFunc) {
          data = data.map(item => this.props.dataMapFunc(item));
        }
        this.setState({
          data
        });
      });
  }

  handleChange = (value) => {
    this.setState({value});
    let {onChange} = this.props;
    if (onChange) {
      onChange(value);
    }
  };

  render() {
    const options = this.state.data.map(d => <Option key={d.code}>{d.text}</Option>);

    return (
      <Select
        value={this.state.value}
        placeholder={this.props.placeholder}
        style={this.props.style}
        onChange={this.handleChange}
      >
        {options}
      </Select>
    );
  }
}

AsyncSelect.propTypes = {
  style: PropTypes.object,
  placeholder: PropTypes.string,
  value: PropTypes.string, // 默认值
  url: PropTypes.string,
  dataMapFunc: PropTypes.func,
  onChange: PropTypes.func,
};

dataMapFunc 是做数据适配的可选参数,默认数据格式是 {code:1,text:'选项1'}

使用

<AsyncSelect url="/api/project-exit-strategies" />

AsyncSelect 既可以用在 Form 中,也可以单独使用

上一篇 下一篇

猜你喜欢

热点阅读