将React图标作为props传递给NextJS中的客户端组件。

huangapple go评论107阅读模式
英文:

Pass React Icon as props to Client Component in NextJS

问题

I build a dynamic button:

'use client';

import type { IconType } from 'react-icons';

interface ButtonProps {
  children: React.ReactNode;
  Icon: IconType;
}

export default function Button(props: ButtonProps) {
  const { children, Icon } = props;

  return (
    <button>
      <Icon />
      {children}
    </button>
  );
}

I got a problem when passing React Icon as props:

Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".
  <... Icon={function} children=...>
```.

I have no idea how to insert 'use server' into React Icon component?

<details>
<summary>英文:</summary>

I build a dynamic button:
```ts
&#39;use client&#39;;

import type { IconType } from &#39;react-icons&#39;;

interface ButtonProps {
  children: React.ReactNode;
  Icon: IconType;
}

export default function Button(props: ButtonProps) {
  const { children,  Icon } = props;

  return (
    &lt;button&gt;
      &lt;Icon /&gt;
      {children}
    &lt;/button&gt;
  );
}

I got a problem when passing React Icon as props:

Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with &quot;use server&quot;.
&lt;... Icon={function} children=...&gt;
.

I have no idea how to insert 'use server' into React Icon component?

答案1

得分: 4

从服务器组件传递到客户端组件的属性需要可序列化,因为它们会通过网络传输。组件是一个函数,这就是为什么您看到了该错误消息。

Icon组件是从哪里来的?您可以直接在客户端组件中导入它吗?

英文:

Props passed from server components to client components need to be serializable, since they're sent across the network. A component is a function, which is why you're seeing that error message.

Where is the Icon component coming from? Can you just import it directly in the client component instead?

huangapple
  • 本文由 发表于 2023年5月17日 09:12:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76267974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定