我在 Next.js 中使用 typewriter-effect 库,但它导致了此错误:
错误:水合失败,因为初始 UI 与原来的 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;
//内容.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;
这是因为您已将
{TypeEffect()}
内容嵌套在 Content.tsx 内的段落 <p>
标签内。这是 next.js 的一个已知问题。有一个问题。在这个问题中,他们得出的结论是,因为 p 标签内的嵌套内容不是有效的 HTML,所以他们不会修复它。
如果将 p 标签变成 div 标签,问题就会消失:
<div className='font-montserrat absolute font-regular md:text-2xl'>
{TypeEffect()}
</div>
顺便说一句,这与打字机效果库无关。如果您在原始代码中的同一个 p 标记内嵌套一个空 div 并且根本不使用打字机效果,您会得到相同的错误。
我正在使用 Next JS 14.2.3,我尝试在 body 标签内使用打字机,但它对我不起作用,相反我使用了这个运行良好的库: