【问题标题】:Why does sx prop typecheck fail?为什么 sx 道具类型检查失败?
【发布时间】:2021-10-24 05:18:50
【问题描述】:

我正在尝试在 React 应用中使用基于 sx prop 的样式。°

我想通过所谓的theme getter 访问主题。

当我尝试使用这种方法时,我可以看到样式在浏览器中呈现正常。然而 TypeScript 抱怨,我发现理解类型血统并弄清楚它在说什么具有挑战性。

Working沙盒

Not working沙盒

完全错误:

No overload matches this call.
  Overload 2 of 2, '(props: DefaultComponentProps<BoxTypeMap<{}, "div">>): Element', gave the following error.
    Type 'string' is not assignable to type 'SystemStyleObject<Theme>'.
  Overload 2 of 2, '(props: DefaultComponentProps<BoxTypeMap<{}, "div">>): Element', gave the following error.
    Type '(theme: any) => { border: string; }' is not assignable to type 'SystemStyleObject<Theme>'.
      Type '(theme: any) => { border: string; }' is not assignable to type 'CSSSelectorObject<Theme>'.ts(2769)
app.tsx(8, 22): Did you mean to call this expression?

可能相关的 GH 讨论 1, 2

大概我应该通过显式设置SystemStyleObject,但不确定从哪里导入它。任何指针将不胜感激。

° 应用使用 TypeScript 4.4.1-rc + MUI 5.0.0-beta.4

【问题讨论】:

    标签: reactjs typescript material-ui emotion


    【解决方案1】:

    它的输入方式。主题功能只能应用于 CSS 样式,不能应用于类。您可以像这样将其向下移动到边框:

      <Box
        sx={{
          border: "1px solid red",
          ".some-child": {
            border: (theme) => {
              return "1px solid green";
            }
          }
        }}
      >
    

    【讨论】:

    【解决方案2】:

    这对我有用:

    import { SxProps } from '@mui/system';
    import { Theme } from '@mui/material/styles';
    
    const style: SxProps<Theme> = {
      position: 'absolute',
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
      width: '100%',
      maxWidth: 900,
      bgcolor: 'background.paper',
      border: '1px solid #a7a7a7',
      boxShadow: 24,
      p: 4,
    }
    
    ...
    
    <Box sx={style}>
    

    【讨论】:

    • 感谢分享您的解决方案!我们希望避免在所有组件中依赖这些类型。我们正在切换到 styled() API 以避免这个问题
    猜你喜欢
    • 2017-07-31
    • 2016-07-08
    • 2021-09-15
    • 1970-01-01
    • 2020-08-26
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多