我有如下的代码使用antd/Dropdown组件:
const items: MenuProps["items"] = [
{
label: <div onClick={() => {
console.log('收藏: ')
}}>收藏</div>,
key: '0',
},
{
label: <a>2nd menu item</a>,
key: '1',
},
{
type: 'divider',
},
{
label: '3rd menu item',
key: '3',
},
];
...
<Dropdown
key={nodeData.key}
menu={{ items }}
trigger={['click']}
open={isOpenObj[nodeData.key]}
onOpenChange={()=>{
updateIsOpenObj(nodeData.key, false)
}}
>
<a onClick={(e) => {
e.preventDefault()
}}>
<Space>
</Space>
</a>
</Dropdown>
这样使用是没有问题的:
调用打开dropdown:
但是我修改为此代码(使用genDropdownItems()
生成items,而不直接传递items,就会报错):
// 生成dropdown的key
const genDropdownItems = (key: string | number): MenuProps["items"] => {
const items: MenuProps["items"] = [
{
label: <div onClick={() => {
console.log('收藏: ', key)
}}>收藏</div>,
key: '0',
},
{
label: <a>2nd menu item</a>,
key: '1',
},
{
type: 'divider',
},
{
label: '3rd menu item',
key: '3',
},
];
return items
}
<Dropdown
key={nodeData.key}
//menu={{ items }}
menu={genDropdownItems(nodeData.key)}
trigger={['click']}
open={isOpenObj[nodeData.key]}
onOpenChange={()=>{
updateIsOpenObj(nodeData.key, false)
}}
>
<a onClick={(e) => {
e.preventDefault()
}}>
<Space>
</Space>
</a>
</Dropdown>
报错结果:
Unhandled Runtime Error
Error: React.Children.only expected to receive a single React element child.
Call Stack
Object.onlyChild [as only]
...
at PathnameContextProviderAdapter (webpack-internal:///../node_modules/.pnpm/registry.npmmirror.com+next@13.5.2_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/shared/lib/router/adapters.js:79:11)
at ErrorBoundary (webpack-internal:///../node_modules/.pnpm/registry.npmmirror.com+next@13.5.2_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/@next/react-dev-overlay/dist/client.js:2:5389)
at ReactDevOverlay (webpack-internal:///../node_modules/.pnpm/registry.npmmirror.com+next@13.5.2_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/@next/react-dev-overlay/dist/client.js:2:7785)
at Container (webpack-internal:///../node_modules/.pnpm/registry.npmmirror.com+next@13.5.2_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/client/index.js:78:1)
at AppContainer (webpack-internal:///../node_modules/.pnpm/registry.npmmirror.com+next@13.5.2_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/client/index.js:182:11)
at Root (webpack-internal:///../node_modules/.pnpm/registry.npmmirror.com+next@13.5.2_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/client/index.js:396:11)
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
你少了对{}吧