【问题标题】:How to create a react portal within ant-design dropdown overlay如何在 ant-design 下拉覆盖中创建反应门户
【发布时间】:2021-09-20 16:58:42
【问题描述】:

我正在使用ant-design Dropdown 组件,其中包含右键单击操作。

我希望能够一次增加 5 或 10。但是,每当单击它时,它都会忽略 Menu.Item 的 onClick 侦听器。

const App = () => {
  const [counter, setCounter] = useState(1);

  const menu = (
    <Menu>
      <Menu.Item key="five" onClick={() => setCounter(counter + 5)}>
        by 5
      </Menu.Item>
      <Menu.Item key="ten" onClick={() => setCounter(counter + 10)}>
        by 10
      </Menu.Item>
    </Menu>
  );

  return (
    <div>
      <p>Counter: {counter}</p>
      <div onClick={() => setCounter(counter + 1)} style={STYLING}>
        <p>Click here to increment</p>
        <Dropdown overlay={menu} trigger={["contextMenu"]}>
          <span>
            Right click here for custom increment
          </span>
        </Dropdown>
      </div>
    </div>
  );
};

代码沙盒示例:https://codesandbox.io/s/contextmenu-with-dropdown-antd-n4c5i?file=/index.js

我尝试过使用 ReactDOM.createPortal,但我就是不知道如何在这样的场景中正确使用它。

我知道我可能不应该使用 createPortal 解决方案,但我需要它的原因不是为了这个简单的示例,而是我希望在 ant-design 表列标题中具有此功能,同时还具有排序功能支持。

【问题讨论】:

    标签: javascript reactjs antd react-portal


    【解决方案1】:

    我想我不需要使用传送门。相反,我可以使用stopPropagation 来防止任何父节点获得 onClick 事件。

    Menu.Item onClick 事件中,标准javascript 事件在domEvent 字段下可用。

    所以我们可以这样创建一个函数:

    const menuOnClick = (amount) => (e) => {
      e.domEvent.stopPropagation();
      setCounter(counter + amount);
    };
    

    并将我们的Menu.Item onClick 回调更新为此

    <Menu.Item key="five" onClick={menuOnClick(5)}>
    

    沙盒示例:https://codesandbox.io/s/contextmenu-with-dropdown-antd-solution-8029o?file=/index.js

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 2019-12-28
      • 2021-09-17
      • 2020-06-14
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      相关资源
      最近更新 更多