【问题标题】:Pass object to material ui styled component将对象传递给材质 ui 样式的组件
【发布时间】:2021-12-10 23:42:32
【问题描述】:

我有一个样式组件:

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 文档中的示例,但似乎无法正常工作。

【问题讨论】:

  • 你能创建一个codesandbox吗?
  • 这能回答你的问题吗? Material-UI v5 passing props to CSS theme
  • @NearHuscarl 不完全是。好像我有一些打字错误。
  • 打字稿错误可以在this答案中修复,你不需要使用OverridableComponent,没必要。

标签: reactjs typescript material-ui


【解决方案1】:

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

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 并在 cmets 中提到问题

【讨论】:

  • 我也这么认为,但Type '{ children: Element[]; movie: any; }' is not assignable to type 'IntrinsicAttributes &amp; SystemProps&lt;Theme&gt; 不这么认为。
  • 好的,@PeterBoomsma,更新解决了你的类型问题吗?
  • codesandbox.io/s/… 让它工作。您是否有一些关于 OverridableComponent 的文档的链接?在 mui 网站上找不到。
  • 不,我只是用电影增强了自己的建议类型,我想source code可以帮助但没有那么多;如果您发现了什么,请告诉我,我们可以在这里发布以供后代使用
  • 可以使用更短的代码在this答案中修复打字稿错误,自定义道具不需要OverridableComponent
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 2020-05-20
相关资源
最近更新 更多