问题描述
我想通过增加图标大小来制作悬停效果,图标来自反应图标,我正在使用样式组件。我该怎么做?
export const BottomBar = () => {
const style = { fontSize: "180%" };
return (
<StyledBottomBar>
<StyledIcon>
<FaFacebookSquare style={style} />
</StyledIcon>
<StyledIcon>
<GrInstagram style={style} />
</StyledIcon>
<StyledIcon>
<CgMail style={style} />
</StyledIcon>
<StyledIcon>
<BiPhoneCall style={style} />
</StyledIcon>
</StyledBottomBar>
);
};
谢谢!!!
解决方法
无法执行内联样式的操作,例如 :hover
。您可以使用 JS 方法 onMouseEnter
和 onMouseLeave
:
const style = { fontSize: "180%",transition: 'font-size 0.5s' };
...
<FaFacebookSquare style={style} onMouseEnter={({target})=>target.style.fontSize= "180%"}
onMouseLeave={({target})=>target.style.fontSize= "100%"}/>
或者你可以将它们分成组件 <StyledIcon/>
和 useRef
、useEffect
和 useState
来进行悬停。
const style = { fontSize: "180%",transition: 'font-size 0.5s' };
export function StyledIcon(props){
const [hover,setHover] = useState(false)
const iconRef = useRef(null)
useEffect(()=>{
if(hover){
iconRef.current.style.fontSize="200%"
}
else{
iconRef.current.style.fontSize="180%"
}
},[hover]) // changing fontSize whenever the hover state is updated
const handleIconType = ()=>{
switch(props.type){
case 'facebook':
{
return <FaFacebookSquare style={style} ref={iconRef} onMouseEnter={()=>{setHover(true)}} onMouseLeave={()=>{setHover(false)}}/>
}
...// cases for different type of icon
default:
return null
}
}
return(
<>
<FaFacebookSquare style={style} ref={iconRef} onMouseEnter={()=>{setHover(true)}} onMouseLeave={()=>{setHover(false)}}/>
</>
)
}
export const BottomBar = () => {
return (
<StyledBottomBar>
<StyledIcon type="facebook">
</StyledIcon>
<StyledIcon type="instagram">
</StyledIcon>
</StyledBottomBar>
);
};
,
因此 react-icons 将呈现为 <svg>
元素。这些属性具有您可以使用样式覆盖的属性,您只能通过对元素本身的操作来操作它们。
在您的示例中,如果您查看开发工具并检查 html,则 svg 元素周围可能有一个 div 包装器,这意味着您尝试应用于它们的样式已应用于 div。
const style = { fontSize: "180%",transition: 'font-size 0.5s' }
//Try writing it like this:
const style = {
'& svg': {
fontSize: '180%',transition: 'fontSize 0.5s'
}
}
这里我们将这些规则应用于 svg 元素而不是它的包装器。
编辑 如果您想收听点击或悬停,请收听包装 svg 的 div!确保它也具有相同的尺寸。