React TSX中particles-bg的JS配置转TS解决ctx隐式any报错
React+TS项目particles-bg配置类型报错解决
报错原因
Parameter 'ctx' implicitly has an 'any' type报错是TypeScript的类型校验触发的,你需要给onParticleUpdate回调的两个入参显式声明类型。
解决步骤
- 定义粒子对象的类型接口,可根据实际用到的属性扩展:
interface Particle { p: { x: number; y: number; }; radius: number; color: string; }
- 给回调函数的入参添加类型:
ctx是Canvas 2D渲染上下文,固定类型为CanvasRenderingContext2Dparticle是粒子实例,类型为上面定义的Particle
完整适配TS的代码
import ParticlesBg from "particles-bg"; import SignIn from "./SignIn"; // 替换为你实际的SignIn组件导入路径 // 定义粒子实例类型 interface Particle { p: { x: number; y: number; }; radius: number; color: string; // 若用到粒子的其他属性,可在此补充定义 } export default function YourPageComponent() { const config = { num: [4, 7], rps: 0.1, radius: [5, 40], life: [1.5, 3], v: [2, 3], tha: [-40, 40], alpha: [0.6, 0], scale: [1, 0.1], position: "center", color: ["random", "#ff0000"], cross: "dead", random: 15, g: 5, // 给参数添加类型声明,解决隐式any报错 onParticleUpdate: (ctx: CanvasRenderingContext2D, particle: Particle) => { ctx.beginPath(); ctx.rect(particle.p.x, particle.p.y, particle.radius * 2, particle.radius * 2); ctx.fillStyle = particle.color; ctx.fill(); ctx.closePath(); } }; return ( <div> <SignIn /> <ParticlesBg type="custom" config={config} bg={true} /> </div> ) }
临时快速解决方法(不推荐)
如果不需要严格类型校验,也可以直接给参数设置any类型跳过校验:
onParticleUpdate: (ctx: any, particle: any) => { // 原有逻辑不变 }
内容的提问来源于stack exchange,提问作者QS123
相关产品推荐
相关产品推荐

