打字机效果库导致 Next.js 中的 Hydration 失败

und*_*ind 3 next.js

我在 Next.js 中使用打字机效果库,但它导致了此错误:

错误:水合失败,因为初始 UI 与服务器上呈现的内容不匹配。

我按照文档中的说明修复了尝试在组件呈现时通过 useEffect 在状态中添加打字机的错误,但它不起作用。我不明白为什么会导致这个错误。

我的代码://TypeEffect.tsx

import Typewriter from 'typewriter-effect';

const TypeEffect = () => {
  const strings = [
    'modern & innovative digital solutions.',
    'e-commerces, web systems, landing pages, blogs & much more.',
    'front-end & back-end development.',
    'UX &UI best pratices.',
  ];

  return (
    <Typewriter
      options={{
        autoStart: true,
        loop: true,
      }}
      onInit={(typewriter) => {
        typewriter
          .typeString(strings[0])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .typeString(strings[1])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .typeString(strings[2])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .typeString(strings[3])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .start();
      }}
    />
  );
};

export default TypeEffect;
Run Code Online (Sandbox Code Playgroud)

//内容.tsx

import React from 'react';
import TypeEffect from '../TypeEffect';

const Content = () => {
  return (
    <main className='mx-auto px-2 select-none font-anton md:-translate-y-24 md:-translate-x-24'>
      <h1 className='text-6xl md:text-7xl mb-4'>
        creative developer
        <span className='text-primary'>.</span>
      </h1>

      <p className='font-montserrat absolute font-regular md:text-2xl'>
        {TypeEffect()}
      </p>
    </main>
  );
};

export default Content;
Run Code Online (Sandbox Code Playgroud)

Ric*_*h N 5

这是因为您已将{TypeEffect()}内容嵌套在 Content.tsx 内的段落<p>标记内。这是 next.js 的一个已知问题。这里面有一个问题。在本期中,他们得出的结论是,由于 p 标签内的嵌套内容不是有效的 HTML,因此他们不会修复它。

如果你将 p 标签变成 div 标签,问题就消失了:

  <div className='font-montserrat absolute font-regular md:text-2xl'>
    {TypeEffect()}
  </div>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这与打字机效果库无关。如果您将空 div 嵌套在原始代码中的同一 p 标记内并且根本不使用打字机效果,则会出现相同的错误。