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" />
网友评论