这是一个样式组件代码块,它获取一个img道具,并基于该道具决定加载特定图像。
export const DialogBanner = styled.div`
min-height: 250px;
margin-bottom: 20px;
${({ img }) =>
img
? `background-image: url(${img});`
: `background-image: url("/img/banner.jpg");`}
background-position: center;
background-size: cover;
filter: contrast(85%);
`;
<DialogBanner img={food.img} />
如何使用Material UI的useStyles编写相同的内容?
答案 0 :(得分:0)
使用Material-UI的最新版本,您将使用makeStyles
,它会创建一个在组件内使用的钩子。 https://material-ui.com/styles/basics/#adapting-based-on-props
例如。
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
// Create our styles using passed props
// These are `functors` it seems
const useStyles = makeStyles({
root: {
backgroundImage: ({ img }) =>
img
? `url(${img});`
: `url("/img/banner.jpg");`}
},
});
function DialogBanner(props) {
// Separating out our children
const { children, ...rest } = props
// Prop containing our `img`
const classes = useStyles(rest);
retun <div className={classes.root>{children}</div>
}