Select选择器

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

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

    基本使用。

    Select 选择器 - 图2

    多选

    多选,从已有条目中选择(scroll the menu)

    1. const Option = Select.Option;
    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. );

    tags select,随意输入的内容(scroll the menu)

    1. import { Select } from 'antd';
    2. const Option = Select.Option;
    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. ReactDOM.render(
    11. <Select mode="tags" style={{ width: '100%' }} placeholder="Tags Mode" onChange={handleChange}>
    12. {children}
    13. </Select>,
    14. mountNode,
    15. );

    Select 选择器 - 图4

    联动

    省市联动是典型的例子。

    1. import { Select } from 'antd';
    2. const Option = Select.Option;
    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. this.setState({
    15. cities: cityData[value],
    16. secondCity: cityData[value][0],
    17. });
    18. };
    19. onSecondCityChange = value => {
    20. this.setState({
    21. secondCity: value,
    22. });
    23. };
    24. render() {
    25. const { cities } = this.state;
    26. return (
    27. <div>
    28. <Select
    29. defaultValue={provinceData[0]}
    30. style={{ width: 120 }}
    31. onChange={this.handleProvinceChange}
    32. >
    33. {provinceData.map(province => (
    34. <Option key={province}>{province}</Option>
    35. ))}
    36. </Select>
    37. <Select
    38. style={{ width: 120 }}
    39. value={this.state.secondCity}
    40. onChange={this.onSecondCityChange}
    41. >
    42. {cities.map(city => (
    43. <Option key={city}>{city}</Option>
    44. ))}
    45. </Select>
    46. </div>
    47. );
    48. }
    49. }
    50. ReactDOM.render(<App />, mountNode);

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

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

    1. import { Select } from 'antd';
    2. const Option = Select.Option;
    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. );

    Select 选择器 - 图6

    搜索用户

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

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

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

    Select 选择器 - 图8

    带搜索框

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

    1. import { Select } from 'antd';
    2. const Option = Select.Option;
    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.Option;
    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. 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

    OptGroup 进行选项分组。

    搜索框

    搜索和远程数据结合。

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

    试下复制 露西,杰克 到输入框里。只在 tags 和 multiple 模式下可用。

    1. import { Select } from 'antd';
    2. const Option = Select.Option;
    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. ReactDOM.render(
    11. <Select mode="tags" style={{ width: '100%' }} onChange={handleChange} tokenSeparators={[',']}>
    12. {children}
    13. </Select>,
    14. mountNode,
    15. );

    扩展菜单

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

    1. import { Select, Icon, Divider } from 'antd';
    2. const Option = Select.Option;
    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. );
    1. <select>
    2. </select>