typescript 向Mui v5 AppBar组件添加自定义样式

fkvaft9z  于 2023-06-30  发布在  TypeScript
关注(0)|答案(1)|浏览(131)

我在Typescript中向Mui v5 AppBar组件添加自定义样式时遇到问题。

import { alpha } from '@mui/material/styles';

export function bgBlur(props: { color: any; blur?: any; opacity?: any; imgUrl?: any; }) {
  const color = props?.color || '#000000';
  const blur = props?.blur || 6;
  const opacity = props?.opacity || 0.8;
  const imgUrl = props?.imgUrl;

  if (imgUrl) {
    return {
      position: 'relative',
      backgroundImage: `url(${imgUrl})`,
      '&:before': {
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 9,
        content: '""',
        width: '100%',
        height: '100%',
        backdropFilter: `blur(${blur}px)`,
        WebkitBackdropFilter: `blur(${blur}px)`,
        backgroundColor: alpha(color, opacity),
      },
    };
  }

  return {
    backdropFilter: `blur(${blur}px)`,
    WebkitBackdropFilter: `blur(${blur}px)`,
  };
}

我在这里调用bgBlur

const StyledAppBar = styled(AppBar)(({ theme }) => ({
  ...bgBlur({ color: theme.palette.background.default }),
  boxShadow: "none",
}))  as typeof AppBar;

错误是
没有重载与此调用匹配。最后一个重载给出了以下错误。

axr492tv

axr492tv1#

这是因为Typescript期望position属性是Property.Position(在cssstyle/index.d.ts中定义),但不能正确推断relative属于这个联合类型。
添加as const修复了错误。

const bgBlur = (props: {
  color: any;
  blur?: any;
  opacity?: any;
  imgUrl?: any;
}) => {
  const color = props?.color || "#000000";
  const blur = props?.blur || 6;
  const opacity = props?.opacity || 0.8;
  const imgUrl = props?.imgUrl;

  return imgUrl
    ? {
        position: "relative" as const // <-- here,
        backgroundImage: `url(${imgUrl})`,
        "&:before": {
          position: "absolute",
          top: 0,
          left: 0,
          zIndex: 9,
          width: "100%",
          height: "100%",
          backdropFilter: `blur(${blur}px)`,
          WebkitBackdropFilter: `blur(${blur}px)`,
        },
      }
    : {
          backdropFilter: `blur(${blur}px)`,
          WebkitBackdropFilter: `blur(${blur}px)`,
      };
};

const StyledAppBar = styled(AppBar)(({ theme }) => ({
  ...bgBlur({ color: theme.palette.background.default }),
  boxShadow: "none",
}));

相关问题