ant-design/components/select/demo/custom-dropdown-menu.md
afc163 1e88248903
docs: renew Select dropdownRender demo and FAQ (#36665)
* docs: renew Select dropdownRender FAQ and demo

* chore: update snapshot

* chore: fix Select demo tsc

* chore: fix Select demo tsc
2022-07-23 17:00:19 +08:00

2.0 KiB

order title
21
zh-CN en-US
扩展菜单 Custom dropdown

zh-CN

使用 open 对下拉菜单进行自由扩展。如果希望点击自定义内容后关闭浮层,你需要使用受控模式自行控制(codesandbox)。

en-US

Customize the dropdown menu via dropdownRender. If you want to close the dropdown after clicking the custom content, you need to control open prop, here is an codesandbox.

import { PlusOutlined } from '@ant-design/icons';
import { Divider, Input, Select, Space, Button } from 'antd';
import type { InputRef } from 'antd';
import React, { useState, useRef } from 'react';

const { Option } = Select;

let index = 0;

const App: React.FC = () => {
  const [items, setItems] = useState(['jack', 'lucy']);
  const [name, setName] = useState('');
  const inputRef = useRef<InputRef>(null);

  const onNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const addItem = (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();
    setItems([...items, name || `New item ${index++}`]);
    setName('');
    setTimeout(() => {
      inputRef.current?.focus();
    }, 0);
  };

  return (
    <Select
      style={{ width: 300 }}
      placeholder="custom dropdown render"
      dropdownRender={menu => (
        <>
          {menu}
          <Divider style={{ margin: '8px 0' }} />
          <Space style={{ padding: '0 8px 4px' }}>
            <Input
              placeholder="Please enter item"
              ref={inputRef}
              value={name}
              onChange={onNameChange}
            />
            <Button type="text" icon={<PlusOutlined />} onClick={addItem}>
              Add item
            </Button>
          </Space>
        </>
      )}
    >
      {items.map(item => (
        <Option key={item}>{item}</Option>
      ))}
    </Select>
  );
};

export default App;