Select选择器

    • 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。

    • 当选项少时(少于 5 项),建议直接将选项平铺,使用 Radio 是更好的选择。

    基本使用。

    Select选择器 - 图2

    多选

    多选,从已有条目中选择。

    1. const { Option } = Select;
    2. const children = [];
    3. for (let i = 10; i < 36; i++) {
    4. children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
    5. }
    6. function handleChange(value) {
    7. console.log(`selected ${value}`);
    8. }
    9. ReactDOM.render(
    10. <Select
    11. mode="multiple"
    12. style={{ width: '100%' }}
    13. placeholder="Please select"
    14. defaultValue={['a10', 'c12']}
    15. onChange={handleChange}
    16. >
    17. {children}
    18. </Select>,
    19. mountNode,
    20. );

    使用 optionLabelProp 指定回填到选择框的 Option 属性。

    1. import { Select } from 'antd';
    2. const { Option } = Select;
    3. function handleChange(value) {
    4. console.log(`selected ${value}`);
    5. }
    6. ReactDOM.render(
    7. <Select
    8. mode="multiple"
    9. style={{ width: '100%' }}
    10. placeholder="select one country"
    11. defaultValue={['china']}
    12. onChange={handleChange}
    13. optionLabelProp="label"
    14. >
    15. <Option value="china" label="China">
    16. <span role="img" aria-label="China">
    17. 🇨🇳{' '}
    18. </span>
    19. China (中国)
    20. </Option>
    21. <Option value="usa" label="USA">
    22. <span role="img" aria-label="USA">
    23. 🇺🇸{' '}
    24. </span>
    25. USA (美国)
    26. </Option>
    27. <Option value="japan" label="Japan">
    28. <span role="img" aria-label="USA">
    29. 🇯🇵{' '}
    30. </span>
    31. Japan (日本)
    32. </Option>
    33. <Option value="koean" label="Koean">
    34. <span role="img" aria-label="USA">
    35. 🇰🇷{' '}
    36. </span>
    37. Koean (韩国)
    38. </Option>
    39. </Select>,
    40. mountNode,
    41. );

    Select选择器 - 图4

    分组

    OptGroup 进行选项分组。

    1. import { Select } from 'antd';
    2. const { Option, OptGroup } = Select;
    3. function handleChange(value) {
    4. console.log(`selected ${value}`);
    5. }
    6. ReactDOM.render(
    7. <Select defaultValue="lucy" style={{ width: 200 }} onChange={handleChange}>
    8. <OptGroup label="Manager">
    9. <Option value="jack">Jack</Option>
    10. <Option value="lucy">Lucy</Option>
    11. </OptGroup>
    12. <OptGroup label="Engineer">
    13. <Option value="Yiminghe">yiminghe</Option>
    14. </OptGroup>
    15. </Select>,
    16. mountNode,
    17. );

    搜索和远程数据结合。

    1. import { Select } from 'antd';
    2. import jsonp from 'fetch-jsonp';
    3. import querystring from 'querystring';
    4. const { Option } = Select;
    5. let timeout;
    6. let currentValue;
    7. function fetch(value, callback) {
    8. if (timeout) {
    9. clearTimeout(timeout);
    10. timeout = null;
    11. }
    12. currentValue = value;
    13. function fake() {
    14. const str = querystring.encode({
    15. code: 'utf-8',
    16. q: value,
    17. });
    18. jsonp(`https://suggest.taobao.com/sug?${str}`)
    19. .then(response => response.json())
    20. .then(d => {
    21. if (currentValue === value) {
    22. const { result } = d;
    23. const data = [];
    24. result.forEach(r => {
    25. data.push({
    26. value: r[0],
    27. text: r[0],
    28. });
    29. });
    30. callback(data);
    31. }
    32. });
    33. }
    34. timeout = setTimeout(fake, 300);
    35. }
    36. class SearchInput extends React.Component {
    37. state = {
    38. data: [],
    39. value: undefined,
    40. };
    41. handleSearch = value => {
    42. fetch(value, data => this.setState({ data }));
    43. };
    44. handleChange = value => {
    45. this.setState({ value });
    46. };
    47. render() {
    48. const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
    49. return (
    50. <Select
    51. showSearch
    52. value={this.state.value}
    53. placeholder={this.props.placeholder}
    54. style={this.props.style}
    55. defaultActiveFirstOption={false}
    56. filterOption={false}
    57. onSearch={this.handleSearch}
    58. onChange={this.handleChange}
    59. notFoundContent={null}
    60. >
    61. {options}
    62. </Select>
    63. );
    64. }
    65. }
    66. ReactDOM.render(<SearchInput placeholder="input search text" style={{ width: 200 }} />, mountNode);

    Select选择器 - 图6

    试下复制 到输入框里。只在 tags 和 multiple 模式下可用。

    扩展菜单

    使用 dropdownRender 对下拉菜单进行自由扩展。

    1. import { Select, Icon, Divider } from 'antd';
    2. const { Option } = Select;
    3. ReactDOM.render(
    4. <Select
    5. defaultValue="lucy"
    6. style={{ width: 120 }}
    7. dropdownRender={menu => (
    8. <div>
    9. {menu}
    10. <Divider style={{ margin: '4px 0' }} />
    11. <div style={{ padding: '8px', cursor: 'pointer' }}>
    12. <Icon type="plus" /> Add item
    13. </div>
    14. </div>
    15. )}
    16. >
    17. <Option value="jack">Jack</Option>
    18. <Option value="lucy">Lucy</Option>
    19. </Select>,
    20. mountNode,
    21. );

    Select选择器 - 图8

    展开后可对选项进行搜索。

    1. import { Select } from 'antd';
    2. const { Option } = Select;
    3. function onChange(value) {
    4. console.log(`selected ${value}`);
    5. }
    6. function onBlur() {
    7. console.log('blur');
    8. }
    9. function onFocus() {
    10. console.log('focus');
    11. }
    12. function onSearch(val) {
    13. console.log('search:', val);
    14. }
    15. ReactDOM.render(
    16. <Select
    17. showSearch
    18. style={{ width: 200 }}
    19. placeholder="Select a person"
    20. optionFilterProp="children"
    21. onChange={onChange}
    22. onFocus={onFocus}
    23. onBlur={onBlur}
    24. onSearch={onSearch}
    25. filterOption={(input, option) =>
    26. option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    27. }
    28. >
    29. <Option value="jack">Jack</Option>
    30. <Option value="lucy">Lucy</Option>
    31. <Option value="tom">Tom</Option>
    32. </Select>,
    33. mountNode,
    34. );

    三种大小

    三种大小的选择框,当 size 分别为 largesmall 时,输入框高度为 40px24px ,默认高度为 32px

    1. import { Select, Radio } from 'antd';
    2. const { Option } = Select;
    3. const children = [];
    4. for (let i = 10; i < 36; i++) {
    5. children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
    6. }
    7. function handleChange(value) {
    8. console.log(`Selected: ${value}`);
    9. }
    10. class SelectSizesDemo extends React.Component {
    11. state = {
    12. size: 'default',
    13. };
    14. handleSizeChange = e => {
    15. this.setState({ size: e.target.value });
    16. };
    17. render() {
    18. const { size } = this.state;
    19. return (
    20. <div>
    21. <Radio.Group value={size} onChange={this.handleSizeChange}>
    22. <Radio.Button value="large">Large</Radio.Button>
    23. <Radio.Button value="default">Default</Radio.Button>
    24. <Radio.Button value="small">Small</Radio.Button>
    25. </Radio.Group>
    26. <br />
    27. <br />
    28. <Select size={size} defaultValue="a1" onChange={handleChange} style={{ width: 200 }}>
    29. {children}
    30. </Select>
    31. <br />
    32. <Select
    33. mode="multiple"
    34. size={size}
    35. placeholder="Please select"
    36. defaultValue={['a10', 'c12']}
    37. onChange={handleChange}
    38. style={{ width: '100%' }}
    39. >
    40. {children}
    41. </Select>
    42. <br />
    43. <Select
    44. mode="tags"
    45. size={size}
    46. placeholder="Please select"
    47. defaultValue={['a10', 'c12']}
    48. onChange={handleChange}
    49. style={{ width: '100%' }}
    50. >
    51. {children}
    52. </Select>
    53. </div>
    54. );
    55. }
    56. }
    57. ReactDOM.render(<SelectSizesDemo />, mountNode);
    1. .code-box-demo .ant-select {
    2. margin: 0 8px 10px 0;
    3. }
    4. #components-select-demo-search-box .code-box-demo .ant-select {
    5. margin: 0;
    6. }

    Select选择器 - 图10

    联动

    省市联动是典型的例子。

    推荐使用 组件。

    1. import { Select } from 'antd';
    2. const { Option } = Select;
    3. const provinceData = ['Zhejiang', 'Jiangsu'];
    4. const cityData = {
    5. Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
    6. Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
    7. };
    8. class App extends React.Component {
    9. state = {
    10. cities: cityData[provinceData[0]],
    11. secondCity: cityData[provinceData[0]][0],
    12. };
    13. handleProvinceChange = value => {
    14. cities: cityData[value],
    15. secondCity: cityData[value][0],
    16. });
    17. };
    18. onSecondCityChange = value => {
    19. this.setState({
    20. secondCity: value,
    21. });
    22. };
    23. const { cities } = this.state;
    24. return (
    25. <div>
    26. <Select
    27. defaultValue={provinceData[0]}
    28. style={{ width: 120 }}
    29. onChange={this.handleProvinceChange}
    30. >
    31. {provinceData.map(province => (
    32. <Option key={province}>{province}</Option>
    33. ))}
    34. </Select>
    35. <Select
    36. style={{ width: 120 }}
    37. value={this.state.secondCity}
    38. onChange={this.onSecondCityChange}
    39. >
    40. {cities.map(city => (
    41. <Option key={city}>{city}</Option>
    42. ))}
    43. </Select>
    44. </div>
    45. );
    46. }
    47. }
    48. ReactDOM.render(<App />, mountNode);

    Select选择器 - 图12

    获得选项的文本

    默认情况下 onChange 里只能拿到 value,如果需要拿到选中的节点文本 label,可以使用 labelInValue 属性。

    选中项的 label 会被包装到 value 中传递给 onChange 等函数,此时 value 是一个对象。

    1. import { Select } from 'antd';
    2. const { Option } = Select;
    3. function handleChange(value) {
    4. console.log(value); // { key: "lucy", label: "Lucy (101)" }
    5. }
    6. ReactDOM.render(
    7. <Select
    8. labelInValue
    9. defaultValue={{ key: 'lucy' }}
    10. style={{ width: 120 }}
    11. onChange={handleChange}
    12. >
    13. <Option value="jack">Jack (100)</Option>
    14. <Option value="lucy">Lucy (101)</Option>
    15. </Select>,
    16. mountNode,
    17. );

    一个带有远程搜索,防抖控制,请求时序控制,加载状态的多选示例。

    1. import { Select, Spin } from 'antd';
    2. import debounce from 'lodash/debounce';
    3. const { Option } = Select;
    4. class UserRemoteSelect extends React.Component {
    5. constructor(props) {
    6. super(props);
    7. this.lastFetchId = 0;
    8. this.fetchUser = debounce(this.fetchUser, 800);
    9. }
    10. state = {
    11. data: [],
    12. value: [],
    13. fetching: false,
    14. };
    15. fetchUser = value => {
    16. console.log('fetching user', value);
    17. this.lastFetchId += 1;
    18. const fetchId = this.lastFetchId;
    19. this.setState({ data: [], fetching: true });
    20. fetch('https://randomuser.me/api/?results=5')
    21. .then(response => response.json())
    22. .then(body => {
    23. if (fetchId !== this.lastFetchId) {
    24. // for fetch callback order
    25. return;
    26. }
    27. const data = body.results.map(user => ({
    28. text: `${user.name.first} ${user.name.last}`,
    29. value: user.login.username,
    30. }));
    31. this.setState({ data, fetching: false });
    32. });
    33. };
    34. handleChange = value => {
    35. this.setState({
    36. value,
    37. data: [],
    38. fetching: false,
    39. });
    40. };
    41. render() {
    42. const { fetching, data, value } = this.state;
    43. return (
    44. <Select
    45. mode="multiple"
    46. labelInValue
    47. value={value}
    48. placeholder="Select users"
    49. notFoundContent={fetching ? <Spin size="small" /> : null}
    50. filterOption={false}
    51. onSearch={this.fetchUser}
    52. onChange={this.handleChange}
    53. style={{ width: '100%' }}
    54. >
    55. {data.map(d => (
    56. <Option key={d.value}>{d.text}</Option>
    57. ))}
    58. </Select>
    59. );
    60. }
    61. }
    62. ReactDOM.render(<UserRemoteSelect />, mountNode);

    Select选择器 - 图14

    隐藏已选择选项

    隐藏下拉列表中已选择的选项。

    1. import { Select } from 'antd';
    2. const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];
    3. class SelectWithHiddenSelectedOptions extends React.Component {
    4. state = {
    5. selectedItems: [],
    6. };
    7. handleChange = selectedItems => {
    8. this.setState({ selectedItems });
    9. };
    10. render() {
    11. const { selectedItems } = this.state;
    12. const filteredOptions = OPTIONS.filter(o => !selectedItems.includes(o));
    13. return (
    14. <Select
    15. mode="multiple"
    16. placeholder="Inserted are removed"
    17. value={selectedItems}
    18. onChange={this.handleChange}
    19. style={{ width: '100%' }}
    20. >
    21. {filteredOptions.map(item => (
    22. <Select.Option key={item} value={item}>
    23. {item}
    24. </Select.Option>
    25. ))}
    26. </Select>
    27. );
    28. }
    29. }