React中实现带悬停动画的perspective透视变换问题求助
问题分析与解决方案
核心问题
你代码里的主要问题有两个:
- React内联样式不支持CSS伪类(如:hover),所以你定义的
perspectiveLeft:hover、perspectiveRight:hover这类规则完全无效。 - Material UI的
Box组件属性写错了,你用了styles,但正确的属性是sx(适配MUI样式系统)或style(原生内联样式);同时内层空Box的结构冗余,应该把透视效果直接应用到带背景图的容器上。
修正后的代码示例(用MUI sx属性实现悬停效果)
import React from 'react'; import { Box } from '@mui/material'; function Perspective() { return ( <Box sx={{ display: 'flex', gap: '2rem', padding: '2rem' }}> {/* 左侧透视卡片 */} <Box sx={{ display: 'inline-block', boxSizing: 'border-box', margin: '1rem', width: '240px', height: '320px', padding: '8px', borderRadius: '1rem', background: 'url(https://picsum.photos/id/1049/240/320)', boxShadow: 'rgba(0, 0, 0, 0.25) 0px 25px 50px -12px', transform: 'perspective(1500px) rotateY(15deg)', transition: 'transform 1s ease 0s', '&:hover': { transform: 'perspective(3000px) rotateY(5deg)', }, }} /> {/* 右侧透视卡片 */} <Box sx={{ display: 'inline-block', boxSizing: 'border-box', margin: '1rem', width: '240px', height: '320px', padding: '8px', borderRadius: '1rem', background: 'url(https://picsum.photos/id/1049/240/320)', boxShadow: 'rgba(0, 0, 0, 0.25) 0px 25px 50px -12px', transform: 'perspective(1500px) rotateY(-15deg)', transition: 'transform 1s ease 0s', '&:hover': { transform: 'perspective(3000px) rotateY(-5deg)', }, }} /> </Box> ); } export { Perspective };
关键修改点
- 替换样式属性:用MUI的
sx属性替代原生内联样式,sx支持伪类语法(&:hover),能正常触发悬停效果。 - 简化结构:把透视、过渡和悬停规则直接绑定到带背景图的
Box上,去掉冗余的空嵌套元素。 - 整合样式逻辑:将分散的样式规则合并到每个卡片的
sx配置中,逻辑更清晰。
可选方案(用styled API分离样式)
如果偏好样式与组件分离,可使用MUI的styled API创建复用组件:
import React from 'react'; import { Box, styled } from '@mui/material'; const PerspectiveCard = styled(Box)<{ direction: 'left' | 'right' }>(({ direction }) => ({ display: 'inline-block', boxSizing: 'border-box', margin: '1rem', width: '240px', height: '320px', padding: '8px', borderRadius: '1rem', background: 'url(https://picsum.photos/id/1049/240/320)', boxShadow: 'rgba(0, 0, 0, 0.25) 0px 25px 50px -12px', transform: `perspective(1500px) rotateY(${direction === 'left' ? '15deg' : '-15deg'})`, transition: 'transform 1s ease 0s', '&:hover': { transform: `perspective(3000px) rotateY(${direction === 'left' ? '5deg' : '-5deg'})`, }, })); function Perspective() { return ( <Box sx={{ display: 'flex', gap: '2rem', padding: '2rem' }}> <PerspectiveCard direction="left" /> <PerspectiveCard direction="right" /> </Box> ); } export { Perspective };
内容的提问来源于stack exchange,提问作者user18943198
相关产品推荐
相关产品推荐

