ant-design/components/select/demo/select-users.md

87 lines
1.9 KiB
Markdown
Raw Normal View History

2017-03-22 14:21:24 +08:00
---
order: 12
title:
zh-CN: 搜索用户
en-US: Search and Select Users
---
## zh-CN
2019-05-09 20:43:12 +08:00
一个带有远程搜索,防抖控制,请求时序控制,加载状态的多选示例。
2017-03-22 14:21:24 +08:00
## en-US
A complete multiple select sample with remote search, debounce fetch, ajax callback order flow, and loading state.
2019-05-07 14:57:32 +08:00
```jsx
2017-03-22 14:21:24 +08:00
import { Select, Spin } from 'antd';
2018-03-08 13:36:12 +08:00
import debounce from 'lodash/debounce';
2018-06-27 15:55:04 +08:00
const { Option } = Select;
2017-03-22 14:21:24 +08:00
class UserRemoteSelect extends React.Component {
constructor(props) {
super(props);
this.lastFetchId = 0;
this.fetchUser = debounce(this.fetchUser, 800);
}
2018-06-27 15:55:04 +08:00
2017-03-22 14:21:24 +08:00
state = {
data: [],
value: [],
fetching: false,
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
2019-05-07 14:57:32 +08:00
fetchUser = value => {
2017-03-22 14:21:24 +08:00
console.log('fetching user', value);
this.lastFetchId += 1;
const fetchId = this.lastFetchId;
2017-12-13 18:49:00 +08:00
this.setState({ data: [], fetching: true });
2017-03-22 14:21:24 +08:00
fetch('https://randomuser.me/api/?results=5')
.then(response => response.json())
2019-05-07 14:57:32 +08:00
.then(body => {
if (fetchId !== this.lastFetchId) {
// for fetch callback order
2017-03-22 14:21:24 +08:00
return;
}
const data = body.results.map(user => ({
text: `${user.name.first} ${user.name.last}`,
value: user.login.username,
}));
2017-12-13 18:49:00 +08:00
this.setState({ data, fetching: false });
2017-03-22 14:21:24 +08:00
});
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
2019-05-07 14:57:32 +08:00
handleChange = value => {
2017-03-22 14:21:24 +08:00
this.setState({
value,
data: [],
fetching: false,
});
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
2017-03-22 14:21:24 +08:00
render() {
const { fetching, data, value } = this.state;
return (
<Select
mode="multiple"
2017-03-22 14:21:24 +08:00
labelInValue
value={value}
placeholder="Select users"
notFoundContent={fetching ? <Spin size="small" /> : null}
filterOption={false}
onSearch={this.fetchUser}
onChange={this.handleChange}
style={{ width: '100%' }}
>
2019-05-07 14:57:32 +08:00
{data.map(d => (
<Option key={d.value}>{d.text}</Option>
))}
2017-03-22 14:21:24 +08:00
</Select>
);
}
}
ReactDOM.render(<UserRemoteSelect />, mountNode);
2019-05-07 14:57:32 +08:00
```