reactjs - MUI sx 道具中的动态样式?
问题描述
是否可以在 MUI sx 道具中使用动态样式?像这样的东西:
<Box
key={index}
sx={{
height: "100%",
width: "100%",
{index === imgIndex &&
{"@keyframes fadeIn": {
from: {
opacity: 0,
},
to: {
opacity: 1,
},
},
"fade-in": {
animation: "$fadeIn 2.5s",
}}}
}}
>
{child}
</Box>
如果没有,有什么选择可以做这样的事情?
我的用例是这是对使用 MUI4(makeStyles)完成的轮播的重构,我正在迁移到 MUI5(不再使用 makeStyles)
解决方案
您可以通过对属性本身而不是在对象内部设置条件来做到这一点。
这是一个示例,说明如何在单击按钮时更改框的 bgColor
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
export default function BoxSx() {
const [clicked, setClicked] = React.useState(false);
const handleClick = () => {
setClicked(!clicked);
};
return (
<>
<Button onClick={handleClick}>Change</Button>
<Box
sx={{
width: 300,
height: 300,
bgcolor: clicked ? "primary.dark" : "secondary.light",
}}
/>
</>
);
}
推荐阅读
- public-key - 使用 bitcoin-abc 从公钥获取比特币现金地址
- node.js - 如何使用 Express.js 和 Angular 修复护照 - twitter 登录的 CORS 错误?
- python - 如何分组/合并具有各种数据类型的数据框
- python - Python Flask_MYSQLDB 问题
- python - 转储 jsons 并在文件名中包含日期
- c# - C# 二进制文件发布请求
- talend - 如何在 Talend 中将特定字符串转换为日期
- android - Xamarin:无法从 Windows VM 连接到在 Mac 上运行的虚拟 Android 设备
- r - 使用下拉框选择过滤 Plotly 条形图
- python - 计算二维数组中的出现次数