Material-UI:`css` 函数已弃用。请改用 `styleFunctionSx`

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

我有一个基于 mui-org/material-ui 的组件库 dot-components。我有另一个正在使用我的 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)

有问题的控制台警告与 mui-org/material-ui PR #23454 however I have gone through my application as well as dot-components and have confirmed we are not using Box at all. I've looked through all of stack overflow and searched everywhere I could online. I even tried asking about it in 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;
  `}
`;

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

正在导入包

    @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 

您的问题有几个方面:

1。为什么要执行 Box 代码及其 use of the css function

在评论中,您提到您正在进行命名导入,例如 import {Button} from "@material-ui/core"。这可能是安全的,并在此处详细讨论:https://material-ui.com/guides/minimizing-bundle-size/#when-and-how-to-use-tree-shaking; but if you haven't taken steps mentioned in that guide, then doing a named import from @material-ui/core (especially in development mode such as when unit tests are executing) will execute the entire index.js 在该包的根目录中,其中包括导入 Box.

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

此弃用警告来自此处:https://github.com/mui-org/material-ui/blob/v4.12.1/packages/material-ui-system/src/styleFunctionSx.js#L69. The reason you are getting the warning is because you are using a newer version (4.12.1) of @material-ui/system than the version (4.11.4) you are using for @material-ui/core. The 4.12.1 version of Box 不再使用 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"; 来消除警告,这样可以避免在根 [=22] 中执行任何代码=] (sandbox here),但是我绝对建议将 @material-ui/core 的版本更新到 4.12.3,以便它与 @material-ui/system 的 4.12.1 的预期完全同步。