SpeechSynthesisUtterance 未定义 NextJS 中的错误

问题描述 投票:0回答:1

我试图让“SpeechSynthesis”说出“Hello world”,但它给了我一个错误。 SpeechSynthesisUtterance 未定义。当我第一次尝试它时,它可以工作,但是当我使用“npm run dev”重新启动服务器时,它会出现错误。

有办法解决这个问题吗?

这是代码:

export default function Main() {
  let text = new SpeechSynthesisUtterance("Hello world!");

  return <button onClick={SpeechSynthesis.speak(text)}>Click me</button>;
}

提前致谢:)

javascript next.js speech-synthesis
1个回答
0
投票

window
SpeechSynthesisUtterance
无法在服务器端访问,所以将它们移至客户端渲染,如下所示:

      <button onClick={() => {
        window.speechSynthesis.speak(new SpeechSynthesisUtterance("Hello world!"))
      }}>Click me
      </button>
© www.soinside.com 2019 - 2024. All rights reserved.