Antd Dropdown子元素为React组件时无法正常工作
AntD Dropdown 组件子元素为函数组件时失效的解决方法
问题原因
AntD 的 Dropdown 组件需要直接给可交互的 DOM 元素(如 Button、a 标签)绑定点击事件和获取 ref 来实现下拉逻辑。当用 <A/> 作为子元素时,A 是独立的函数组件,Dropdown 会把事件绑定在 A 组件本身而非内部的 Button,但 A 组件没有将这些事件透传给内部元素,导致点击无法触发下拉;而 {A()} 是直接执行函数返回 Button DOM 节点,Dropdown 能直接操作这个节点,所以功能正常。
解决方案
方法1:透传所有 props 给内部元素
修改 A 组件,将接收到的所有 props 传递给内部的 Button,让 Dropdown 绑定的事件能作用到实际可点击的元素上:
import { Dropdown, Button } from 'antd'; import { memo } from 'react'; import type { MenuProps } from 'antd'; const headerMeau: MenuProps['items'] = [ { key: '1', label: 'test' }, { key: '2', label: 'test2' }, { key: '3', label: 'test3' } ]; // 修改A组件,透传props const A = function (props) { return <Button {...props}>111</Button>; }; const BookSpace = memo(() => { return ( <Dropdown menu={{ items: headerMeau }} placement="bottomLeft" trigger={['click']}> <A></A> </Dropdown> ); }); BookSpace.displayName = 'BookSpace'; export default BookSpace;
方法2:使用 forwardRef 转发 ref(更严谨)
Dropdown 可能需要获取子元素的 ref 来做定位等操作,用 React.forwardRef 把 ref 转发给内部的 Button,确保组件交互和定位都正常:
import { Dropdown, Button } from 'antd'; import { memo, forwardRef } from 'react'; import type { MenuProps } from 'antd'; const headerMeau: MenuProps['items'] = [ { key: '1', label: 'test' }, { key: '2', label: 'test2' }, { key: '3', label: 'test3' } ]; // 用forwardRef包裹A组件,转发ref和props const A = forwardRef((props, ref) => { return <Button ref={ref} {...props}>111</Button>; }); A.displayName = 'A'; // 给组件设置displayName,方便调试 const BookSpace = memo(() => { return ( <Dropdown menu={{ items: headerMeau }} placement="bottomLeft" trigger={['click']}> <A></A> </Dropdown> ); }); BookSpace.displayName = 'BookSpace'; export default BookSpace;
内容的提问来源于stack exchange,提问作者富贵花开
相关产品推荐
相关产品推荐

