next.js 当试图调用按钮的onClick方法内部的方法时,它会抛出错误[重复]

xn1cxnb4  于 2023-06-22  发布在  其他
关注(0)|答案(5)|浏览(248)

此问题已在此处有答案

Next.js - having trouble setting up an onClick handler(1个答案)
5天前关闭。
这篇文章是编辑并提交审查5天前.
我刚开始学习Next.js,想尝试一些简单的东西。我想在我的页面上显示一个按钮,当点击时,会在控制台中显示“点击”。
这是我添加到page.js中的默认模板中的代码,该模板是在运行npx create-next-app时生成的。

export default function Home() {
    const handleClick() => {
        console.log('clicked');
    }
    return (
        <div>
            <button onClick={handleClick} >Click me</button>
        </div>
    )
}

当我试着运行这个的时候它抛出了错误
到目前为止我试过的修复方法…。

return (
        <div>
            <button onClick={() => handleClick} >Click me</button>
        </div>
)

这抛出了一个错误

error Error: Event handlers cannot be passed to Client Component props.
  <button onClick={function} children=...>
                  ^^^^^^^^^^
If you need interactivity, consider converting part of 
this to a Client Component.
   at stringify (<anonymous>)
digest: "1701345382"
null

我也试过

return (
            <div>
                <button onClick={(handleClick} >Click me</button>
            </div>
    )

它也抛出了同样的错误

v6ylcynt

v6ylcynt1#

onClick属性需要一个函数,所以...

onClick={() => handleClick()}

这样,您就传递了一个不带参数的匿名函数,该函数调用不带参数的handleClick
您还可以:

onClick={(event) => handleClick(event)}

这样,您就将event属性传递给了handleClick函数。
或者

onClick={handleClick}

这样,您就可以将每个参数传递给handleClick函数。这和写作是一样的

onClick={(event, ...params) => handleClick(event, ...params)}

最后,当你写

onClick={handleClick()}

handleClick()不是一个函数,它是从handleClick函数返回的。

wwwo4jvm

wwwo4jvm2#

接下来js默认在服务器端呈现页面。但事件发生在浏览器中。因此,在nextjs文件的顶部,提到“使用客户端”,它会将组件转换为客户端。

'use client'

import { useState } from 'react'

export default function Counter() {
  const [count, setCount] = useState(0)
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>)}

请参阅Next js文档:https://nextjs.org/docs/getting-started/react-essentials#the-use-client-directive

zaqlnxep

zaqlnxep3#

我在做一些React时学到的是:(如果我错了请纠正)
如果我们使用箭头函数传递onclick处理程序,那么您将不得不调用handleClick函数。
尝试将其更改为:
<button onClick={() => handleClick()}> Click me </button>
(we需要()后的函数在这里)
如果我们希望在handleClick函数中传递一些参数,则主要使用此语法。
否则,我们也可以这样做:
<button onClick={handleClick}> Click me </button>
(we在这里不需要()函数之后)
如果我们做了:
<button onClick={handleClick()}> Click me </button>
那么handleClick函数将在页面上呈现的同时执行这行代码时运行而无需单击按钮。
就像发生在你身上一样!希望有帮助:D

5w9g7ksd

5w9g7ksd4#

您是否尝试过将该组件转换为客户端组件,并在文件顶部添加'use client';Because all components in Next by default are server components,因此对于客户端交互,您需要使用“使用客户端”。

u0njafvf

u0njafvf5#

试试用这个

const handleClick=()=>{
           console.log("clicked")
       }

相关问题