Material-UI:“css”函数已弃用。使用“styleFunctionSx”代替

CWS*_*tes 11 reactjs material-ui styled-components

我有一个dot-components基于mui-org/material-ui. 我有另一个应用程序正在使用我的dot-components组件库,最近我注意到我的单元测试中出现了控制台警告。

控制台警告

    console.warn
      Material-UI: The `css` function is deprecated. Use the `styleFunctionSx` instead.

      at css (../../node_modules/@material-ui/system/styleFunctionSx.js:75:13)
      at Object.<anonymous> (../../node_modules/@material-ui/core/Box/Box.js:14:37)
      at Object.<anonymous> (../../node_modules/@material-ui/core/Box/index.js:21:36)
Run Code Online (Sandbox Code Playgroud)

有问题的控制台警告与mui-org/material-ui PR #23454有关,但我已经检查了我的应用程序并确认我们根本dot-components没有使用。Box我已经浏览了所有堆栈溢出并在网上搜索了所有可以搜索的地方。我什至尝试在mui-org/material-ui #27799中询问这个问题,但是他们更关心解决问题而不是实际提供帮助。

我在这里没有选择,我唯一能想到的是 MUI 发出警告,因为它看到css我的样式组件中使用了

样式化组件示例

import styled, { css } from 'styled-components';

export const StyledProductInstancesList = styled.div``;

export const StyledCard = styled(DotCard)`
  ${({ theme }) => css`
    margin-bottom: ${theme.spacing(1)}px;
  `}
`;
Run Code Online (Sandbox Code Playgroud)

我将一个沙箱与我所看到的问题的非常清晰的最小示例放在一起。

正在导入的包

    @material-ui/core:  4.11.4 
    @material-ui/styles:  4.11.4 
    @material-ui/system:  4.12.1 
    @material-ui/types:  5.1.0 
    @material-ui/utils:  4.11.2 
    @types/react: 16.9.56 => 16.9.56 
    react: 17.0.1 => 17.0.1 
    react-dom: 17.0.1 => 17.0.1 
    styled-components: 5.2.1 => 5.2.1 
    typescript: ~4.0.3 => 4.0.7 
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 14

您的问题有几个方面:

1. 为什么要执行CSS函数的Box代码及其使用?

在评论中您提到您正在执行命名导入,例如import {Button} from "@material-ui/core". 这是安全的,详细讨论如下: https: //material-ui.com/guides/minimizing-bundle-size/#when-and-how-to-use-tree-shaking;但如果您尚未采取该指南中提到的步骤,则执行命名导入@material-ui/core(尤其是在开发模式下,例如执行单元测试时)将执行该包根目录中的整个index.jsBox ,其中包括 importing 。

2. 为什么导入会Box导致控制台出现有关该css函数已被弃用的警告?

此弃用警告来自此处:https://github.com/mui-org/material-ui/blob/v4.12.1/packages/material-ui-system/src/styleFunctionSx.js#L69。您收到警告的原因是您使用的版本 (4.12.1) 比@material-ui/system您使用的版本 (4.11.4) 更新@material-ui/coreBox 4.12.1 版本不再使用该css功能,因此不会收到此警告。

这是一个非常简单的代码沙箱,通过利用与您相同的版本来重现警告: https: //codesandbox.io/s/css-function-is-deprecated-hjzl2 ?file=/src /App.js。

将版本更新@material-ui/core到 4.12.0 到 4.12.3 之间的任何版本可以解决此沙箱中所示的问题:https://codesandbox.io/s/css-function-is-deprecated-forked-78qo7 ?file=/src/App .js

也可以将@material-ui/core版本保留在 4.11.4 并通过更改导入来消除警告,import Button from "@material-ui/core/Button";然后避免在根目录index.js此处为沙箱)中执行任何代码,但是我绝对建议将版本更新@material-ui/core为 4.12.3,以便与4.12.1的期望完全同步@material-ui/system