Next.js:服务器组件向客户端组件传递回调函数报错求助
解决Next.js 13.4中服务器组件向客户端组件传递onClick回调的报错问题
问题原因
Next.js 13+ App Router下,默认组件为服务器组件。服务器组件在渲染时会将props序列化为JSON传递给客户端组件,但函数无法被序列化,因此直接从服务器组件向客户端组件传递onClick这类事件处理函数会触发报错:
error Error: Event handlers cannot be passed to Client Component props.
解决方案
1. 将父组件转为客户端组件
在WelcomeComponent.tsx顶部添加'use client'指令,使其成为客户端组件,这样就能正常传递函数类型props给子组件:
'use client'; import { faPizzaSlice } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { Brand, Button } from "@/components/Common"; import Image from "next/image"; const WelcomeComponent = () => { return ( <div className="border flex items-center justify-center flex-wrap space-x-10 py-10"> <div className="font-semibold flex flex-col"> <div className="mr-3 flex items-center text-3xl"> <span className="mr-2">Welcome to</span> <Brand size="large" /> </div> <h2 className="text-2xl">We Serve you with happiness.</h2> <Button text="Order Now" icon={<FontAwesomeIcon className="w-6" icon={faPizzaSlice} />} onClick={() => { console.log("c"); }} /> </div> <Image className="w-auto h-auto" height={0} width={300} src="/man.jpg" priority alt="" /> </div> ); }; export default WelcomeComponent;
2. 确保Button组件为客户端组件
包含交互逻辑的Button组件必须标记为客户端组件,在Button.tsx顶部添加'use client':
'use client'; interface Props { text: string; icon: React.JSX.Element; onClick: () => void; } const Button = ({ text, icon, onClick }: Props) => { return ( <button onClick={onClick} className="shadow-lg my-5 flex items-center justify-center text-white bg-orange-400 hover:bg-orange-500 rounded-md p-3 w-40 space-x-2" > <span className="text-md">{text}</span> {icon} </button> ); }; export default Button;
关键说明
服务器组件专注于服务器端渲染,减少客户端JS体积,但无法处理交互逻辑或传递不可序列化的props(如函数)。任何需要响应用户交互的组件,都必须通过'use client'标记为客户端组件。
内容的提问来源于stack exchange,提问作者Tanmay Vaij
相关产品推荐
相关产品推荐

