【问题标题】:Nextjs button onClick does not work after static export静态导出后 Nextjs 按钮 onClick 不起作用
【发布时间】:2021-09-25 02:20:31
【问题描述】:

我有一个非常基本的 Next.js,可以在开发过程中使用。但是当我尝试使用next build & next export 静态导出它时,我无法再单击该按钮。做检查表明没有事件附加到这个按钮

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

我部署到 Netlify 和 Vercel 也有同样的问题,按钮没有 onClick 事件

Console https://onmyway133.com/almighty/ 中有一堆 ERR 404,所以这也很可疑

【问题讨论】:

    标签: reactjs button onclick next.js export


    【解决方案1】:

    您似乎试图直接在浏览器中打开生成的 HTML 文件,但资源未加载(相对路径问题),请参阅开发工具中的网络错误。使用 live serverserve 之类的工具在本地提供代码,它应该可以工作。

    使用服务:

    yarn global add serve # npm install -g serve
    
    yarn next build
    yarn next export
    yarn serve out # npx serve out #-- if you just want to try
    

    更新问题:

    另一种选择是设置assetPrefix(可能不适用于嵌套页面):

    // next.config.js
    
    module.exports = { assetPrefix: './' }; // enforces relative paths
    

    这里正在讨论这个问题:https://github.com/vercel/next.js/issues/2581


    另外,我无法重现您的特定问题:

    GitHub:https://github.com/brc-dd/so-68406279
    韦尔塞尔:https://so-68406279.vercel.app
    网络化:https://stupefied-wright-3d7c4b.netlify.app

    这意味着您的项目结构、配置或部署策略完全存在问题。

    【讨论】:

    • 我部署到 Netlify 和 Vercel 也有同样的问题,按钮没有 onClick 事件
    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 2021-07-06
    • 2018-05-10
    • 1970-01-01
    • 2012-03-26
    • 2015-02-24
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多