在 NextJS 组件中执行 `onClick` 的正确方法是什么?

What's the right way to do `onClick` in a NextJS component?

在使用 NextJS 做我的项目时,我遇到了一个部分,我在其中制作了一个名为 app_buttonGray 看起来像这样:

// /components/app_buttonGray.js
export default function AppButtonGray({ size, children }){
    return(
        <button className={`flex w-${size ? size : "36"} mt-2 p-1 rounded-md bg-gray-500 hover:bg-gray-800 shadow-lg justify-center`}>
            {children}
        </button>
        
    )
}

稍后在我的页面中我想创建多个按钮,但每个按钮都有不同的用途 所以我想像这样实现onClick

<AppButtonGray size="48" onClick={ () => alert(1)}>New project</AppButtonGray>
<AppButtonGray size="48" onClick={ () => alert(2)}>Open project</AppButtonGray>

但这似乎行不通...

经过多方考虑,我想出了使它起作用的修改:

// /components/app_buttonGray.js
export default function AppButtonGray({ size, onClick, children }){
    return(
        <button onClick={onClick} className={`flex w-${size ? size : "36"} mt-2 p-1 rounded-md bg-gray-500 hover:bg-gray-800 shadow-lg justify-center`}>
            {children}
        </button>
        
    )
}

所以我不得不通过参数传递 onClick 然后在组件内部调用它...

这是完成这项工作的正确方法吗?如果不是那么正确的方法是什么?谢谢

是的,这是完成您想要做的事情的正确方法。在 React 中,如果您希望应用它们,您总是必须将任何自定义道具传递给要返回的元素。

然而,实现此目的的另一种方法是使用 rest syntax (...) to grab all of the remaining props passed to your component and spreading 它们到子组件上。

//                                                      Get the remaining props
export default function AppButtonGray({ size, children, ...props }) {
  return (
    <button
      className={`flex w-${
        size || "36"
      } mt-2 p-1 rounded-md bg-gray-500 hover:bg-gray-800 shadow-lg justify-center`}
      {...props}
    >
      {children}
    </button>
  );
}

这是将您想要的任何道具传递给子组件的有效方法,但在尝试理解组件时,它可能会降低可读性。这就是为什么一些 ESLint 配置不允许这种策略 (you can read more about that here).

我个人认为在大多数情况下你应该坚持你的方式,当你试图理解你写的代码时,你会在漫长的 运行 中感谢自己。