我正在使用 Next.js 应用程序路由器开发一个项目。
我有两个组件,一个客户端组件和一个服务器组件。
// Client component
"use client"
export default function Icon({ name, icon, className = '' } : iconType) {
return (
<>
<IconContext.Provider
value={ { size: "45px" } }
>
<div
className={`flex flex-col ${className}`}
>
<div
className="flex justify-center"
>
{ icon }
</div>
<div
className="flex justify-center"
>
{ name }
</div>
</div>
</IconContext.Provider>
</>
)
}
// Server component
...
<div
className="flex justify-center my-10"
>
{ socials.map((social) => (
<>
<Icon
name={ social.name }
icon={ social.icon }
/>
</> ))}
</div>
...
客户端组件中的上下文提供程序应该调整服务器组件中呈现的图标的大小。然而,它并没有这样做。
我尝试通过在顶部添加“use client”指令来使服务器组件成为客户端组件。这使得上下文提供者可以工作。但是,我在服务器组件中进行了一些数据获取,所以我认为这不是一个理想的解决方案。
查阅其他一些文档,我的做法似乎是预期的做法,但我很难弄清楚为什么它没有真正起作用。
不要依赖上下文,而是将所需的大小属性(在本例中为“
size
”)从服务器组件显式传递到 Icon
组件。更新 Icon 组件以接受 size 属性并将其应用到图标:
// Server component
...
<div
className="flex justify-center my-10"
>
{socials.map((social) => (
<>
<Icon
name={social.name}
icon={social.icon}
size="45px" // Pass down the size prop
/>
</>
))}
</div>
...
// Client component (Icon)
export default function Icon({ name, icon, size = '', className = '' } : iconType) {
return (
<>
<div
className={`flex flex-col ${className}`}
style={{ fontSize: size }} // Use the passed down size prop
>
<div className="flex justify-center">{icon}</div>
<div className="flex justify-center">{name}</div>
</div>
</>
);
}