我想随着图标大小的增加而产生悬停效果,图标来自反应图标,我使用的是样式组件。我该怎么做?
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图标将呈现为<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元素,而不是它的包装器。
EDIT如果您想监听点击或悬停,请监听包装svg的div!确保它也有相同的尺寸。