You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next 14自定义描边文本组件出现Hydration失败错误求助

解决Next.js 14中文本外描边组件的Hydration失败问题

问题原因

错误提示“HTML中

不能作为

的子元素”是因为HTML规范禁止<p>元素嵌套任何块级元素(包括<p>本身),而你的StrokeText组件外层是<p>,使用时又传入了<p>作为children,形成了非法嵌套结构。Next.js的Hydration过程会严格校验服务端与客户端的DOM结构一致性,这种非法嵌套会直接导致校验失败,抛出错误。

解决方案

只需两步修改即可解决:

1. 将组件外层的<p>替换为<div>

<div>是通用块级容器,没有嵌套限制,完全适配你的文本样式需求。修改后的组件代码如下:

import React from 'react';
import styles from './styles.module.css';

type StrokeTextType = {
  fontSize: string;
  color: string;
  strokeSize: string;
  strokeColor: string;
  text: string;
  align?: 'left' | 'center' | 'right';
  fontWeight?: number | string;
  margin?: string;
  fontFamily?: string;
  children?: React.ReactNode; // 扩展支持更多子元素类型
};

const StrokeText = ({
  fontSize,
  color,
  strokeSize,
  strokeColor,
  text,
  align,
  fontWeight,
  margin,
  fontFamily,
  children,
}: StrokeTextType) => {
  return (
    <div
      className={styles.text}
      title={text}
      style={
        {
          color,
          fontSize,
          fontWeight,
          fontFamily,
          margin,
          textAlign: align,
          '--stroke-size': strokeSize,
          '--stroke-color': strokeColor,
        } as React.CSSProperties
      }
    >
      {children ?? text}
    </div>
  );
};

export default StrokeText;

2. 调整组件使用方式,移除嵌套的<p>

使用时直接传入文本和内联元素(如<span>)即可,无需外层<p>:

<StrokeText
  text='Ok, you win, but it was close'
  color='white'
  fontSize={isMobile ? '15px' : '20px'}
  strokeSize='5px'
  strokeColor='black'
  fontWeight={400}
  align='center'
  margin={isMobile ? '0 0 10px 0' : '0'}
>
  Ok, you win,{' '}
  <span style={{ color: '#FFCC00' }}>but</span> it was close.
</StrokeText>

额外说明

如果你的styles.module.css中有针对<p>的样式规则,需要同步修改为针对.text类选择器,确保样式正常生效。

内容的提问来源于stack exchange,提问作者Oliver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:55:14