Vanilla-tilt-react为自定义卡片添加额外样式该如何阻止?
解决方案
你可以根据自己的使用场景选择以下任意一种方式解决默认样式注入问题:
方法1:直接通过
style属性覆盖(最快捷)
因为Tilt组件注入的是内联样式,你直接给<Tilt>标签设置的style属性优先级和默认注入样式持平,写在后面的属性会直接覆盖默认值:<Tilt options={{ scale: 2 }} style={{ margin: 0, padding: 0, borderRadius: 0, background: 'transparent', boxShadow: 'none', width: 'auto', color: 'inherit', fontSize: 'inherit', lineHeight: 'inherit' }} > <div className="card"> <div className="pt-3"> <img src={coin.image} style={{width:'10vh'}} className="card-img-top" alt="..."></img> </div> <div className="card-body text-center"> <h4>{coin.name}</h4> <div className=""> <h5>${coin.current_price.toFixed(2)}</h5> <span className="text-success">({coin.price_change_percentage_24h.toFixed(2)}%)</span> </div> </div> </div> </Tilt>注:你原有代码里img标签的
class属性要改成React标准的className才能正常生效。方法2:通过自定义className+CSS全局覆盖(适合多组件复用)
给<Tilt>标签指定自定义类名,再用CSS的!important强制覆盖默认样式:
组件代码:<Tilt className="custom-tilt" options={{ scale: 2 }}> {/* 原有卡片内容 */} </Tilt>CSS代码:
.custom-tilt { margin: 0 !important; padding: 0 !important; border-radius: 0 !important; background: transparent !important; box-shadow: none !important; width: fit-content !important; color: inherit !important; font-size: inherit !important; line-height: inherit !important; }方法3:直接使用原生vanilla-tilt绑定DOM(完全可控无额外样式)
如果你用的是第三方封装的React版Tilt组件才会自带默认样式,直接用原生vanilla-tilt自己绑定到卡片元素上,不需要额外包裹组件,完全不会注入多余样式:import { useRef, useEffect } from 'react' import VanillaTilt from 'vanilla-tilt' function CoinCard({ coin }) { const cardRef = useRef(null) useEffect(() => { // 初始化tilt效果,绑定到你的卡片元素 VanillaTilt.init(cardRef.current, { scale: 2 // 其他tilt配置可自行添加 }) }, []) return ( <div ref={cardRef} className="card"> <div className="pt-3"> <img src={coin.image} style={{width:'10vh'}} className="card-img-top" alt="..."></img> </div> <div className="card-body text-center"> <h4>{coin.name}</h4> <div className=""> <h5>${coin.current_price.toFixed(2)}</h5> <span className="text-success">({coin.price_change_percentage_24h.toFixed(2)}%)</span> </div> </div> </div> ) }
内容的提问来源于stack exchange,提问作者fatihcan8
相关产品推荐
相关产品推荐

