React18下react-awesome-reveal报children属性不存在TS类型错误
React 18 下 react-awesome-reveal 报 children 属性不存在的TS错误解决
问题场景
在React 18 + TypeScript项目中引入react-awesome-reveal实现滚动动画效果,此前在低版本React项目中使用该模块无同类问题,当前触发如下TS类型报错:
Type '{ children: Element; keyframes: Keyframes; triggerOnce: true; }' is not assignable to type 'IntrinsicAttributes & RevealProps'. Property 'children' does not exist on type 'IntrinsicAttributes & RevealProps'.ts(2322)
触发错误的业务代码:
import { Reveal } from "react-awesome-reveal"; import { customizeAnimation } from "config/utils"; export const example = () => { return ( <Reveal keyframes={ customizeAnimation } triggerOnce> <div>业务子节点内容</div> </Reveal> ); };
错误原因
- React 18 调整了内置
FC(函数组件)的类型定义,移除了默认携带的children属性声明,4.1.0以下版本的react-awesome-reveal未同步适配该类型变化,TS校验时无法识别Reveal组件支持传入子节点。 - 项目本地存在多版本
@types/react依赖冲突,导致类型解析异常。 - 升级
react-awesome-reveal到v4版本后未安装要求的peer依赖@emotion/react,触发连带类型错误。
解决方案
按优先级依次尝试以下方案:
- 升级依赖到适配React18的版本(推荐)
执行安装命令升级模块及必需的peer依赖:
安装完成后重启TS服务即可消除报错。npm install react-awesome-reveal@latest @emotion/react@latest - 临时扩展类型绕开校验(暂无法升级时使用)
对Reveal组件做类型扩展,手动补全children属性定义:import { Reveal, RevealProps } from "react-awesome-reveal"; import { customizeAnimation } from "config/utils"; // 补全React18下缺失的children类型定义 const SafeReveal = Reveal as React.FC<RevealProps & { children: React.ReactNode }>; export const example = () => { return ( <SafeReveal keyframes={customizeAnimation} triggerOnce> <div>业务子节点内容</div> </SafeReveal> ); }; - 排查并修复@types/react版本冲突
执行命令检查本地依赖中是否存在多版本@types/react:
如果输出结果显示存在多个不同版本的@types/react,在package.json中添加配置锁定版本(npm 8.3+用overrides,yarn/pnpm用resolutions):npm ls @types/react
修改后重新执行依赖安装命令即可。{ "overrides": { "@types/react": "^18.2.0" } }
内容的提问来源于stack exchange,提问作者Amazing4u
相关产品推荐
相关产品推荐

