MUI Menu组件报错:不接受Fragment作为子元素,寻求解决方案
问题详情
我用MUI写了一个带条件渲染的Menu组件,控制台一直弹出错误:MUI: The Menu component doesn't accept a Fragment as a child. Consider providing an array instead.。
相关代码
<Menu id="basic-menu" anchorEl={anchorEl} open={postSettings} onClose={() => { setPostSettings(false); }} MenuListProps={{ "aria-labelledby": "basic-button", }} > {post?.owner?._id === user._id ? ( <> <MenuItem>Edit</MenuItem> <MenuItem onClick={handleDeletePostClick}>Delete</MenuItem> <ConfirmDelete open={showDeletePostConfirm} handleClose={handleDeletePostCancel} handleConfirm={handleDeletePostConfirm} description="Are you sure you want to delete ?" /> </> ) : ( <MenuItem>Report</MenuItem> )} </Menu>
报错原因
MUI的Menu组件内部实现不支持直接将Fragment(<>或<React.Fragment>)作为子元素,你在条件判断的真分支里用Fragment包裹了多个MenuItem和ConfirmDelete组件,这触发了该报错。
修复方案
方案1:用数组替代Fragment
把Fragment替换成数组,给每个子元素添加唯一的key属性:
<Menu id="basic-menu" anchorEl={anchorEl} open={postSettings} onClose={() => { setPostSettings(false); }} MenuListProps={{ "aria-labelledby": "basic-button", }} > {post?.owner?._id === user._id ? ( [ <MenuItem key="menu-edit">Edit</MenuItem>, <MenuItem key="menu-delete" onClick={handleDeletePostClick}>Delete</MenuItem>, <ConfirmDelete key="confirm-delete" open={showDeletePostConfirm} handleClose={handleDeletePostCancel} handleConfirm={handleDeletePostConfirm} description="Are you sure you want to delete this post?" /> ] ) : ( <MenuItem key="menu-report">Report</MenuItem> )} </Menu>
方案2:用MUI容器组件替代Fragment
可以用<Box>或者<MenuList>(逻辑合适时)来包裹多个子元素,MUI允许这类容器作为Menu的直接子元素:
<Menu id="basic-menu" anchorEl={anchorEl} open={postSettings} onClose={() => { setPostSettings(false); }} MenuListProps={{ "aria-labelledby": "basic-button", }} > {post?.owner?._id === user._id ? ( <Box> <MenuItem>Edit</MenuItem> <MenuItem onClick={handleDeletePostClick}>Delete</MenuItem> <ConfirmDelete open={showDeletePostConfirm} handleClose={handleDeletePostCancel} handleConfirm={handleDeletePostConfirm} description="Are you sure you want to delete this post?" /> </Box> ) : ( <MenuItem>Report</MenuItem> )} </Menu>
额外注意
你原代码里的<ConfirmDelete>标签未闭合,description的字符串也不完整,修复时记得补全这些语法问题,避免引发其他错误。
内容的提问来源于stack exchange,提问作者Abhay Thayyil Mukundan
相关产品推荐
相关产品推荐

