REACT渲染一个空白页面,以导入作为Prop传递的组件并在控制台中给出错误
该应用程序正常运行完美,直到我不使用 Icon
组件sidebaroption.js。一旦我将其放在那里,就会使用控制台呈现一个空白页,然后抛出以下错误
预期的字符串(用于内置组件)或类/函数(对于复合组件),但got:未定义。您可能会忘记从定义的文件中导出组件,或者您可能将默认值混合并命名为导入。
sidebaroption.js
import React from "react";
import "../style/sidebarOption.css";
function SidebarOption({ text, Icon }) {
return (
<div className="sidebarOption">
<h2> {text} </h2>
{/* <Icon/> */}
</div>
);
}
export default SidebarOption;
sixbar.js
import React from 'react'
import '../style/sidebar.css'
import { SidebarOption } from './'
import TwitterIcon from '@mui/icons-material/Twitter';
import HomeIcon from '@mui/icons-material/Home';
import SearchIcon from '@mui/icons-material/Search';
import NotificationsNoneIcon from '@mui/icons-material/NotificationsNone';
function Sidebar() {
return (
<div className="sidebar">
<TwitterIcon />
<SidebarOption Icon={HomeIcon} text='Home'/>
<SidebarOption Icon={SearchIcon} text='Explore'/>
<SidebarOption Icon={NotificationsNoneIcon} text='Notifications'/>
</div>
)
}
export default Sidebar;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道为什么您会根据您在此处显示的代码遇到该错误,但是在您提到的代码和框中,由于您两次没有道具调用侧边栏组件引起的错误。
您只有通过有条件渲染图标就可以通过这样的错误来解决该错误
I don't know why you're getting that error based on the code you showed here, but in the codesandbox you mentioned, the error is due to you calling the sidebar component twice with no props.
You can fix that error like this by conditional render Icon only if it's passed
您正在做的是试图在此处渲染可能不确定的东西:
{/*&lt; icon/&gt; */}
。用{ICON&amp;&amp;替换它。 &lt; icon /&gt;} < /code>检查是否可以渲染道具。
What you are doing is trying to render something that is potentially undefined here:
{/* <Icon/> */}
. Replace this with{Icon && <Icon />}
to check if the prop can be rendered.