在AntD Tab组件中使用Icon时触发缺少指定Prop的警告
解决AntD Tab组件中Icon出现的
[antd: Icon] Should have type/component/children警告 嘿,我刚碰到过类似的问题,这就帮你捋清楚怎么搞定它~
这个警告的核心原因很简单:Ant Design的Icon组件必须要接收type、component属性,或者传入有效的children内容,如果这三个都没有,就会抛出这个提示。在Tab组件里用Icon的时候,很容易因为写法不对触发这个问题,下面给你几个针对性的解决方案:
1. 正确使用AntD内置Icon(分版本)
如果你用的是AntD 3.x版本
确保给Icon传入type属性指定图标类型,比如在Tab的tab属性里这样写:
import { Tabs, Icon } from 'antd'; const { TabPane } = Tabs; <Tabs> <TabPane tab={<><Icon type="user" /> 用户管理</>} key="1" > 这里是用户管理页面内容 </TabPane> </Tabs>
如果你用的是AntD 4.x及以上版本
AntD 4+已经把内置Icon改成了按需引入的独立组件,直接导入对应图标组件使用就好,不用再套一层Icon:
import { Tabs } from 'antd'; import { UserOutlined } from '@ant-design/icons'; const { TabPane } = Tabs; <Tabs> <TabPane tab={<><UserOutlined /> 用户管理</>} key="1" > 这里是用户管理页面内容 </TabPane> </Tabs>
这种写法不仅不会触发警告,还能减少打包体积哦~
2. 使用自定义/第三方图标时的正确姿势
如果你用的是自定义SVG图标或者第三方图标库(比如React Icons),有两种写法:
- 方式一:通过
component属性传入图标组件
import { Tabs, Icon } from 'antd'; import { FaUser } from 'react-icons/fa'; const { TabPane } = Tabs; <Tabs> <TabPane tab={<><Icon component={FaUser} /> 用户管理</>} key="1" > 这里是用户管理页面内容 </TabPane> </Tabs>
- 方式二:直接把图标组件作为children传入(不需要套
Icon)
import { Tabs } from 'antd'; import { FaUser } from 'react-icons/fa'; const { TabPane } = Tabs; <Tabs> <TabPane tab={<><FaUser /> 用户管理</>} key="1" > 这里是用户管理页面内容 </TabPane> </Tabs>
3. 排查代码中的空Icon
最后别忘了检查一下代码里有没有不小心写了<Icon />这种没有任何属性的空标签,这种情况肯定会触发警告,直接删掉或者补充属性就好啦~
内容的提问来源于stack exchange,提问作者Alyssa Reyes
相关产品推荐
相关产品推荐

