NextJS中Swiper内联CSS自定义样式TS类型错误求助
解决NextJS中Swiper内联CSS自定义属性的TypeScript类型错误
我在NextJS中使用Swiper组件,希望不通过全局样式覆盖修改分页和导航样式,又无法用CSS Modules实现,于是用内联CSS设置Swiper自定义属性,结果碰到如下TypeScript类型错误:
Type '{ "--swiper-pagination-color": string; }' is not assignable to type 'Properties<string | number, string & {}>'. Object literal may only specify known properties, and '"--swiper-pagination-color"' does not exist in type 'Properties<string | number, string & {}>'.ts(2322) index.d.ts(1863, 9): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & RefAttributes<SwiperRef> & SwiperProps'
Swiper官方Demo里也用了这种写法,但作为TypeScript新手,不知道怎么解决这个类型报错。我的组件代码如下:
<Swiper loop={true} spaceBetween={10} slidesPerView={1} navigation={true} style={{ "--swiper-pagination-color": "#fff", }} thumbs={{ swiper: thumbsSwiper && !thumbsSwiper.destroyed ? thumbsSwiper : null }} modules={[FreeMode, Navigation, Thumbs]} > {imgs?.map((item, index) => { return ( <SwiperSlide key={index} className={styles.carouselImageDivUpper}> <TransformWrapper> <TransformComponent> <img className={styles.carouselImage} src={item?.s3UrlLink} /> </TransformComponent> </TransformWrapper> </SwiperSlide> ); })} </Swiper>
解决方法
方法1:类型断言(快速解决)
直接把style对象断言为React.CSSProperties,让TypeScript认可自定义CSS变量:
<Swiper // 其他属性不变 style={{ "--swiper-pagination-color": "#fff", } as React.CSSProperties} > {/* 子组件内容 */} </Swiper>
方法2:扩展全局CSS类型(长期规范方案)
在项目根目录或src文件夹下创建globals.d.ts文件,添加自定义属性的类型声明:
declare module 'react' { interface CSSProperties { '--swiper-pagination-color'?: string; // 按需添加其他Swiper自定义属性,比如导航颜色 '--swiper-navigation-color'?: string; } }
之后所有组件里使用这些自定义CSS变量都不会再触发类型错误。
方法3:提前定义样式变量
把样式单独定义为带有类型的变量,再传入组件:
const swiperCustomStyles: React.CSSProperties = { "--swiper-pagination-color": "#fff", }; <Swiper // 其他属性不变 style={swiperCustomStyles} > {/* 子组件内容 */} </Swiper>
这些方法的核心都是告诉TypeScript:自定义CSS变量是合法的样式属性,从而绕过类型检查报错。
内容的提问来源于stack exchange,提问作者Ankit Sharma
相关产品推荐
相关产品推荐

