ReactJS MUI Box如何在onclick后创建平滑的css过渡



我有这个沙盒。这是一种基于div的切换组件方法,但是我想为状态添加一个平滑的转换,例如在这个示例https://codepen.io/nikkk-me/pen/abvPjeG中。我说:

after: {
transform: 'translateX(120px)',
transition: 'transform 300ms linear'
}

在样式div中,但它不起作用。有关于如何解决这个问题的提示吗?

尽管添加的代码中存在语法错误,但似乎您希望通过动画化伪元素来创建这种效果。

这是可以做到的,但是需要编写一个完整的自定义组件,这有点与使用MUI的目的相矛盾。

无论如何,这里有一个简单的例子:

Live demo: sandbox

// demo.tsx
import * as React from "react";
import { styled } from "@mui/material/styles";
import { Box, Typography } from "@mui/material";
const Selector = styled(Box)(({ selected }) => ({
display: "flex",
justifyContent: "center",
cursor: "pointer",
color: selected ? "white" : "inherit",
borderRadius: selected ? "21px" : "unset",
padding: "3px 20px 3px 20px",
width: "50px",
zIndex: "100",
transition: "color 0.2s linear"
}));
export default function BoxSx() {
const [selected, setSelected] = React.useState("first");
function handleSelected() {
setSelected(selected === "first" ? "second" : "first");
}
return (
<Box
sx={{
display: "flex",
background: "grey",
width: "fit-content",
borderRadius: "25px",
p: "2px",
isolation: "isolate",
position: "relative",
"&::before": {
content: "''",
position: "absolute",
backgroundColor: "pink",
padding: "3px 20px 3px 20px",
width: "50px",
borderRadius: "21px",
zIndex: "50",
top: "0",
left: selected === "first" ? "0" : "93px",
bottom: "0",
transition: "left 0.2s linear"
}
}}
onClick={handleSelected}
>
<Selector selected={selected === "first"} color="green">
<Typography sx={{ fontWeight: "bold" }}>First</Typography>
</Selector>
<Selector selected={selected === "second"} color="green">
<Typography sx={{ fontWeight: "bold" }}>Second</Typography>
</Selector>
</Box>
);
}

最新更新