reactjs 如何在Ant设计中获取下拉组件的值(Antd),React js

smdncfj3  于 2023-03-01  发布在  React
关注(0)|答案(3)|浏览(393)

我有一个问题,我不能取出下拉到setState的值或类似的东西。大家都知道如何解决它吗?我试图通过onChange访问它,但仍然不工作。
代码如下:

const menu = (
    <Menu onSelect={(e) => console.log(e)}>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Recommended
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Newest
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Lowest Price
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Highest Price
        </a>
      </Menu.Item>
    </Menu>
  );

<Dropdown overlay={menu1} trigger={['click']}>
            <a
              className="ant-dropdown-link"
              onClick={(e) => e.preventDefault()}
              style={{ color: '#d46b08', fontWeight: 'bold' }}
            >
              PRICE <DownOutlined />
            </a>
</Dropdown> ```
im9ewurl

im9ewurl1#

为了获取下拉菜单中所选菜单的值,需要在每个菜单项上分配一个键,然后可以使用Menu组件的onClick prop来获取值或键。

const handleClick = ({key}) => {
  console.log(key)
  //you can perform setState here
}

const menu = (
  <Menu onClick={handleClick}>
    <Menu.Item key="Recommend">Recommend</Menu.Item>
    <Menu.Item key="Newest">Newest</Menu.Item>
    <Menu.Item key="Lowest Price">Lowest Price</Menu.Item>
    <Menu.Item key="Highest Price">Highest Price</Menu.Item>
  </Menu>
);

<Dropdown overlay={menu} trigger={["click"]}>
    <a
      className="ant-dropdown-link"
      onClick={(e) => e.preventDefault()}
      style={{ color: "#d46b08", fontWeight: "bold" }}
    >
      PRICE <DownOutlined />
    </a>
</Dropdown>

检查其工作here以供参考。

0x6upsns

0x6upsns2#

Dropdown组件不调用任何onChange属性。它有onVisibleChange属性,每次执行“下拉触发器”(悬停、单击、右键单击)时都会调用该属性。请执行以下操作:

const SomeComponent = _props =>
{
  const [visible, setVisible] = React.useState(false);
  
  return (<Dropdown overlay={menu} visible={visible} onVisibleChange={isVisible => setVisible(isVisible)} >
    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
      Hover me <DownOutlined />
    </a>
  </Dropdown>);
}

工作笔here

k5hmc34c

k5hmc34c3#

您可以使用以下各项:

export const items = [
  {
    label: "View Profile",
    key: "view-profile",
  },
];
const handleDropdownItemClick = (e) => {
    console.log(e.key);
  };
<Dropdown
            menu={{
              onClick: handleDropdownItemClick,
              items: items,
            }}
            placement="bottomRight"
            className="text-white"
          >
            <a>
              <Space>
                <DownOutlined />
              </Space>
            </a>
  </Dropdown>

相关问题