本文介绍了将 props 传递给 TS 中的 makeStyle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 post.mainImage
传递给 backgroundImage
样式.
这是我的代码;
import React from 'react';
import { Post } from '../interfaces';
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
type Props = {
post: Post;
}
const useStyles = makeStyles<Theme, Props>((theme: Theme) =>
createStyles({
root: {
maxWidth: '100%',
backgroundImage: ({ post }) => post.mainImage
},
date: {
margin: theme.spacing(1),
marginLeft: theme.spacing(2)
},
heroimage: {
maxWidth: '100%',
height: 'auto',
objectFit: 'cover'
}
})
);
export default function HeroPost({ post }: Props) {
const classes = useStyles({ post });
return (
<Container className={classes.root}>
<img alt={post.title} src={post.mainImage} className={classes.heroimage} />
</Container>
);
}
下面的代码已经顺利通过了linter.但是仍然无法获得前面的 backgroundImage
值.
The code below has passed without a problem from the linter. But still cannot get the backgroundImage
value on the front.
推荐答案
您可以为 makeStyles
的调用提供类型变量(请注意,第一个必须是主题类型,第二个必须是主题类型.类型):
You can supply type variables to the call to makeStyles
(note that the first one must be the theme type and the second the prop type):
type Props = {
post: Post;
};
const useStyles = makeStyles<Theme, Props>(theme =>
createStyles({
root: {
maxWidth: '100%',
backgroundImage: ({ post }) => `url("${post.mainImage}")`
},
// ...
})
);
export default function HeroPost({ post }: Props) {
const classes = useStyles({ post });
return (
// ...
);
}
这篇关于将 props 传递给 TS 中的 makeStyle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!