迁移到Material-UI v5时,如何处理条件类?

2024-02-19

In the 官方迁移指南 https://next.material-ui.com/guides/migration-v4/#main-content,他们给出了以下从 JSS 更改代码的示例(makeStyles)到新的styled mode.

Before:

const useStyles = makeStyles((theme) => ({
    background: theme.palette.primary.main,
}));

function Component() {
    const classes = useStyles();
    return <div className={classes.root} />
}

After:

const MyComponent = styled('div')(({ theme }) => 
    ({ background: theme.palette.primary.main }));

function App(props) {
    return (
        <ThemeProvider theme={theme}>
            <MyComponent {...props} />
        </ThemeProvider>
    );
}

对于单个类来说这很好,但是当代码中有条件类时该怎么办?

e.g.

<main className={classnames(content, open ? contentOpen : contentClosed)}>
    {/* content goes here */}
</main>

Here, content, contentOpen, and contentClosed类是从返回的useStyles, but contentOpen and contentClosed根据以下值有条件地呈现open.

随着新styled方法,我们不是生成类名,而是生成组件。有没有一种方法可以优雅地复制渲染,而无需在三元表达式中进行内容重复?

e.g. we don't想做类似的事情:

function App(props) {
    return (
        <ThemeProvider theme={theme}>
            {open
            ? <MyOpenComponent {...props}>{/* content */}</MyOpenComponent>
            : <MyClosedComponent {...props}>{/* content */}</MyClosedComponent>
        </ThemeProvider>
    );
}

有很多可能的方法来处理这个问题。一种方法使用styled是利用 props 来做动态样式而不是尝试使用多个类。

这是一个例子:

import React from "react";
import Button from "@mui/material/Button";
import { styled } from "@mui/material/styles";

const StyledDiv = styled("div")(({ open, theme }) => {
  const color = open
    ? theme.palette.primary.contrastText
    : theme.palette.secondary.contrastText;
  return {
    backgroundColor: open
      ? theme.palette.primary.main
      : theme.palette.secondary.main,
    color,
    padding: theme.spacing(0, 1),
    "& button": {
      color
    }
  };
});

export default function App() {
  const [open, setOpen] = React.useState(false);
  return (
    <StyledDiv open={open}>
      <h1>{open ? "Open" : "Closed"}</h1>
      <Button onClick={() => setOpen(!open)}>Toggle</Button>
    </StyledDiv>
  );
}

这是使用 TypeScript 的等效示例:

import * as React from "react";
import Button from "@mui/material/Button";
import { styled } from "@mui/material/styles";

const StyledDiv: React.ComponentType<{ open: boolean }> = styled("div")(
  ({ open, theme }) => {
    const color = open
      ? theme.palette.primary.contrastText
      : theme.palette.secondary.contrastText;
    return {
      backgroundColor: open
        ? theme.palette.primary.main
        : theme.palette.secondary.main,
      color,
      padding: theme.spacing(0, 1),
      "& button": {
        color
      }
    };
  }
);

export default function App() {
  const [open, setOpen] = React.useState(false);
  return (
    <StyledDiv open={open}>
      <h1>{open ? "Open" : "Closed"}</h1>
      <Button onClick={() => setOpen(!open)}>Toggle</Button>
    </StyledDiv>
  );
}

其他一些可能的方法:

  • 使用情感cssprop 和 Emotion 的能力作曲风格 https://emotion.sh/docs/composition
  • Use tss-反应 https://github.com/garronej/tss-react保留类似的语法makeStyles但由 Emotion 支持(因此您不会在捆绑包中同时包含 Emotion 和 JSS,如果您利用makeStyles from @material-ui/styles)。这是我迁移到 v5 时采取的路线,作为迁移的一部分,我创建了一个codemod https://mui.com/material-ui/guides/migration-v4/#2-use-tss-react用于迁移 JSSmakeStyles到 tss-react 的makeStyles.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

迁移到Material-UI v5时,如何处理条件类? 的相关文章

随机推荐

  • 查找每个点坐标属于哪个国家/地区[重复]

    这个问题在这里已经有答案了 我有一个带有纬度 经度坐标的数据框 head COORD LAT LON 1 69 34 16 17 2 69 20 17 92 3 69 59 17 87 4 69 17 18 52 5 69 42 18 95
  • 多选 PHP

  • 用 Spirit Qi 解析成 std​​::vector,出现段错误或断言失败

    我使用 Spirit Qi 作为解析器 将数学表达式解析为表达式树 我跟踪诸如解析时遇到的符号类型之类的事情 并且必须在我正在解析的文本中声明这些符号 也就是说 我正在解析贝尔蒂尼输入文件 http bertini nd edu Berti
  • 有 libclang 的教程吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我一直在寻找一些易于理解的 libclang 指南 我在这里或其他论坛上看到了一些帖子 但唯一推荐的信
  • 如何使用 ef core 1 在 UWP 中运行迁移

    我不知道如何使用 EntityFramework Commands 也是 v7 0 0 rc1 final 在 EntityFramework Core v7 0 0 rc1 final 中运行迁移 当我添加迁移 Add Migration
  • Actionscript 3 内省——函数名称

    我试图迭代对象的每个成员 对于每个成员 我检查它是否是一个函数 如果它是一个函数 我想获取它的名称并根据函数的名称执行一些逻辑 我不知道这是否可能 是吗 有小费吗 example var mems Object getMemberNames
  • 如何在 C# 和 DataAnnotation 中创建通用 UniqueValidationAttribute?

    我正在尝试创建一个UniqueAttribute使用System ComponentModel DataAnnotations ValidationAttribute 我希望这是通用的 因为我可以传递 Linq DataContext 表名
  • 在浏览器窗口中更改 PDF 标题

    我有一个 pdf 文件 正在为客户放在网站上 它位于这里 http www optiphysicaltherapy com dev wp content uploads 2014 02 OPTI NewPatientForms pdf ht
  • 如何更改消息框标题? [复制]

    这个问题在这里已经有答案了 如何在asp net中更改此消息框的标题 该标题出现在 IE 中 帮忙 你不能 没有 API 可以执行此操作 默认标题是反网络钓鱼安全功能 如果您希望对警报消息的外观有足够的控制 那么您必须在 DOM 中构建自己
  • CGContextDrawImage 崩溃

    代码如下 void drawLayer CALayer layer inContext CGContextRef ctx CGContextRef context ctx CGContextRetain context CGContextS
  • 应用程序的沙箱虚拟机(概念)

    我想编写一个沙箱虚拟机来执行已编译的程序 我的目标是将该程序与操作系统的其余部分隔离并控制其执行 以便它不会对主机做出任何有害的事情 我假设 执行的程序被编译为可移植可执行格式 并且是机器代码 而不是任何类型的字节代码或 CLR 执行的程序
  • 在 python 中,是否有跨平台的方法来确定哪个进程正在侦听给定端口?

    在linux下 我可以使用lsof i如以下函数所示 def FindProcessUsingPort portnum import os fp os popen lsof i s portnum lines fp readlines fp
  • Android 12 模拟器预览版无连接

    我已经安装了 Android 12 Preview 模拟器 我遇到了很多问题 因为模拟器在启动时崩溃 但在卸载并再次安装并重新启动机器等后 我设法启动它 我现在遇到的问题是互联网连接不起作用 所有其他模拟器都工作正常 我尝试从命令行启动模拟
  • Android:向EditText字段添加小数点,并使其随输入移动

    在我的应用程序中 用户可以在文本字段中输入美元金额 问题是 我需要输入在输入数字时适应最终数字 而不实际输入小数点 解释这一点的最好方法是用一个例子 假设用户从包含以下内容的 EditText 字段开始 用户想要在字段中输入 12 53 即
  • 为 Google App Engine 配置 Jackson

    有什么办法可以配置吗Jackson 配置对象映射器 哪个用于序列化 servlet 响应 Api name rates version v1 title Rates API public class RatesApi static Logg
  • 熊猫,按计数分组并将计数添加到原始数据帧?

    当尝试计算数据框中具有相似 种类 的行时 import pandas as pd items aaa aaa text 1 aaa aaa text 2 aaa aaa text 3 bb bb text 1 bb bb text 2 bb
  • 从 D2006 移植到 XE5 后偶发的访问冲突在 XP 兼容模式下不会发生

    我们有一个在 Delphi 2006 中运行良好的大型应用程序 我们已将其移至 XE5 但经常遇到偶发的访问冲突 我们使用 VCL 表单和许多 DevExpress 以及其他第三方组件 我们正在使用 Windows 7 Profession
  • tess-two 找不到 libpng.so

    我已遵循 tess two 的构建说明Github https github com rmtheis tess two build 我使用 NDK 成功构建了 tess two 并导入了库 我正在尝试运行同一存储库上提供的测试应用程序 但每
  • RTC_WAKEUP 不起作用

    目前我正在开发一个广播接收器应用程序 其中我正在制作一个警报 该警报应该在我们输入秒数后显示一条消息 我使用了 RTC WAKEUP 这意味着它应该在设备打开时显示消息 并且应该打开设备 然后在设备关闭时显示消息 我的问题是 RTC WAK
  • 迁移到Material-UI v5时,如何处理条件类?

    In the 官方迁移指南 https next material ui com guides migration v4 main content 他们给出了以下从 JSS 更改代码的示例 makeStyles 到新的styled mode