首页 > 解决方案 > 将对象传递给材质 ui 样式的组件

问题描述

我有一个样式组件:

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

export const MovieModalStyle = styled(Box)(({theme}) => ({
  // ...
  background: `url(${'https://image.tmdb.org/t/p/w780/' + movie.backdrop_path})`,
}));

我想将movie对象传递给它,以便我可以使用该backdrop_path属性:

<MovieModalStyle movie={movie} />

引用主题旁边的电影道具会返回错误:

styled(Box)(({theme, movie}) => ({
// Error: Property 'movie' does not exist on type 
// IntrinsicAttributes & SystemProps<Theme>

我已经尝试使用https://mui.com/system/styled文档中的示例,但我似乎无法让它工作。

标签: reactjstypescriptmaterial-ui

解决方案


除了主题之外的所有道具都可以在样式包装器中找到。对于打字稿投诉,您可以使用相同的类型,包括电影类型。

import { Box, BoxTypeMap } from "@mui/material";
import { OverridableComponent } from "@mui/material/OverridableComponent";
import {styled} from '@mui/material/styles';

interface Movie {
  backdrop_path: string;
}

export const MovieModalStyle = styled(Box)<{ movie: Movie }>(
  ({ theme, movie }) => ({
    background: `url(${
      "https://image.tmdb.org/t/p/w780/" + movie.backdrop_path
    })`
  })
);

您还可以通过覆盖 Mui 自己的类型从一开始就更改样式化的泛型类型

export const MovieModalStyle = styled<
  OverridableComponent<BoxTypeMap<{ movie: Movie }, "div">>
>(Box)(({ theme, movie }) => ({
  background: `url(${'https://image.tmdb.org/t/p/w780/' + movie.backdrop_path})`,
}));

不要忘记投票给@NearHuscarl 并在评论中提到问题


推荐阅读