我陷入了创建自定义按钮组件,将其标记为客户端组件,然后传递其onClick
来自服务器端组件的回调,它给了我这个错误:
error Error: Event handlers cannot be passed to Client Component props.
<button onClick={function} className=... children=...>
^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.
at stringify (<anonymous>)
digest: "280571554"
这是我的WelcomeComponent.tsx
file:
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;
这是我的Button.tsx
file:
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;
正如你所看到的,我想通过onClick
回调到Button
我在中调用的组件WelcomeComponent.tsx
.
我正在使用 Next.jsv13.4
.
那是因为服务器组件被编译为 HTML 并发送到浏览器,无需额外的 JavaScript,即您的情况下的单击处理程序。这使得您只能将非函数值从服务器组件传递到客户端组件。
调用的组件Button
应该是一个客户端,"use client"
在顶部,因为您需要从那里传递一个函数,这没关系,就像来自 Vercel 的 Lee Robinsonsays:
客户端组件不是取消选择,也不是逃避。您可以将服务器组件视为现有模型的补充。我理解想要在很多事情上使用服务器组件的情绪(不错!),但在某些事情上使用客户端组件也是完全可以的。
"use client"; // Need to send a JavaScript function to the browser ????????
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>
);
};
甚至客户端组件也会首先使用 Next.js 在服务器上呈现,所以如果是为了SEO,就不用担心。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)