[英]pass in external styles to a MUI styled component
Although I have seen similar questions, none seem to address my situation.虽然我见过类似的问题,但似乎没有一个能解决我的情况。
I am migrating MUI v4 to MUI v5, and I've had a love of cases in which a particular style comes externally.我正在将 MUI v4 迁移到 MUI v5,并且我很喜欢外部出现特定样式的情况。 For example, this is what it would look like using makeStyles
:例如,这是使用makeStyles
的样子:
const useStyles = makeStyles((theme) => {
typographyRoot: ({ color }) => ({
padding: theme.spacing(1),
color
})
})
const Example = ({ color }) => {
const classes = useStyles({ color })
return (
<Typography variant="body1" classes={{ root: classes.typographyRoot }}>
Some example
</Typography>
)
}
Now I am attempting to do this using styled
components, how would I pass in the color prop as I did in the useStyles?现在我正在尝试使用styled
化组件来执行此操作,我将如何像在 useStyles 中那样传递颜色道具?
Here is what I currently have:这是我目前拥有的:
const StyledTypography = styled(Typography)(({ theme }) => ({
padding: theme.spacing(1),
color // how to pass in color in this styled component
}))
const Example = ({ color }) => {
return (
<StyledTypography variant="body1">
Some example
</StyledTypography>
)
}
Suppose I could wrap the StyledComponent in a function and pass it in there, but I feel like there must be a more appropriate way to do so.假设我可以将 StyledComponent 包装在 function 中并将其传递到那里,但我觉得必须有更合适的方法来做到这一点。 Specifically:具体来说:
const getStyledTypography = (color) => styled(Typography)(({ theme }) => ({
padding: theme.spacing(1),
color
}))
const Example = ({ color }) => {
const StyledTypography = getStyledTypography(color)
return (
<StyledTypography variant="body1">
Some example
</StyledTypography>
)
}
Anyway, what is the proper way to pass in extra props into a styled component in this fashion?无论如何,以这种方式将额外的道具传递到样式组件中的正确方法是什么?
It should be passed as prop.它应该作为道具通过。
<StyledTypography variant="body1" color={'red'}>
Some example
</StyledTypography>
const StyledTypography = styled(Typography, {
shouldFrowardProp:(prop) => prop !== 'color'
})(({ theme, color }) => ({
padding: theme.spacing(1),
color: color
}))
Use shouldForwardProp to not pass the prop to the dom element.使用 shouldForwardProp 不将 prop 传递给 dom 元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.