reactjs - 将对象传递给材质 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文档中的示例,但我似乎无法让它工作。
解决方案
除了主题之外的所有道具都可以在样式包装器中找到。对于打字稿投诉,您可以使用相同的类型,包括电影类型。
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 并在评论中提到问题
推荐阅读
- bash - 如何遍历列表,忽略列表中的某些元素?
- javascript - 如何在jquery中处理同时发生的点击事件
- c# - 通过 PowerShell 为我的所有站点配置 New-WebHandler
- c++ - 基于伪代码编写的高斯消除中的 std::bad_alloc
- android - 使用 androidx.appcompat 库 FirebaseRecyclerAdapter 无法正常工作
- r - 为每个受试者分配治疗
- ios - 在应用程序顶部发生来电或任何事件时检测 iOS 中的应用程序状态?
- jquery - 超过最大调用堆栈大小 jquery cytoscape
- c# - 如何使用正则表达式检查字符串是否在第二个字符中有字母
- python - SVN 与多个修订版合并 [Not Range]