函数不能直接传递给客户端组件

问题描述 投票:0回答:1

我正在使用 next js 14.0.3,当我将图标从服务器组件传递到客户端组件时,它给出了这个错误

'函数不能直接传递给客户端组件,除非您通过用“使用服务器”标记来显式公开它。'

这是服务器组件

import React from "react";
import { Layout, Compass } from "lucide-react";
import SidebarItem from "./SidebarItem";

const guestRoutes = [
  {
    label: "Home",
    path: "/",
    icon: Layout,
  },
  {
    label: "Browse",
    path: "/search",
    icon: Compass,
  },
];

function SidebarRoutes() {
  const routes = guestRoutes;

  return (
    <div className="flex mt-4 flex-col h-full">
      {routes.map((route) => {
        return (
          <SidebarItem
            key={route.path}
            icon={route.icon}
            label={route.label}
            path={route.path}
          />
        );
      })}
    </div>
  );
}

export default SidebarRoutes;

这是 clinet 组件

'use client';

import React from "react";
import { LucideIcon } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";

interface SidebarItemProps {
  label: string;
  path: string;
  icon: LucideIcon;
}
const SidebarItem = ({ label, icon: Icon, path }: SidebarItemProps) => {
  const router = useRouter();
  const pathname = usePathname();

  return (
    <Icon/>
  );
};

export default SidebarItem;

谁知道我该如何解决

我必须检查条件渲染的路径名,这就是为什么我需要将此组件转换为客户端,我尝试过但没有修复

next.js next.js14
1个回答
0
投票

我遇到了同样的问题并解决了它。解决办法是:

  1. 图标必须是字符串,如下所示:

    const guestRoutes = [
    

    { 标签:“家”, 小路: ”/”, 图标:“布局”, }, { 标签:“浏览”, 路径:“/搜索”, 图标:“指南针”, }, ];

  2. 您必须像这样创建新组件:

    import * as LuIcon from 'lucide-react';
    

    界面 IconCheckProps { 图标:字符串; }

    const IconCheck = ({ icon }: IconCheckProps) => { const IconLibraries = { ...LuIcon }; const IconComponent = IconLibraries[图标作为 IconLibraries 类型的键];

    if (!IconComponent) {
        return null;
    }
    
    return <IconComponent />;
    

    };

导出默认图标检查;

  1. 你可以这样打电话

    界面 SidebarItemProps { 标签:字符串; 路径:字符串; 图标:字符串; }

    const SidebarItem = ({ 标签, 图标, 路径 }: SidebarItemProps) => { const 路由器 = useRouter(); const 路径名 = usePathname();

    返回( ); };

© www.soinside.com 2019 - 2024. All rights reserved.