[英]Material ui emotion/styled how to combine multiple snippets of css classes?
In the old way material ui (version 4 and earlier) styled components you could use className property to "Select" which styles are active, ie a component could be styled like:在旧的材料 ui(版本 4 和更早版本)样式组件中,您可以使用 className 属性来“选择”哪些样式是活动的,即组件的样式可以如下:
const styles = (theme: ThemeTy) => ({
root: {
width: '100%',
},
rootLight: {
color: theme.palette.getContrastText(theme.palette.primary.main),
},
})
const useStyles = makeStyles(styles);
function MyComp() {
const classes = useLocalStyles();
return <Input
className=classNames(classes.root, highContrast ? classes.rootLight : undefined)}
value={100}
/>
}
However in the new api one would define the classes outside the component similar to styled-components does it:然而,在新的 api 中,将定义类似于 styled-components 的组件外部的类:
const StyledInput = styled(Input)(({theme}) => `
width: '100%',
`);
function MyComp() {
return <StyledInput
value={100}
/>
}
However how would I add the conditional styling?但是我将如何添加条件样式? Would I have to use the
sx
element?我必须使用
sx
元素吗? And thus use conditional styling everywhere?因此在任何地方都使用条件样式?
You can pass any props to your StyledInput
and then style the component based on them:您可以将任何道具传递给您的
StyledInput
,然后根据它们为组件设置样式:
const StyledInput = styled(Input)(({ theme, showborders }) => ({
width: "100%",
border: showborders ? "3px solid red" : "none"
}));
...
const [showBorders, setShowBorders] = React.useState(false);
return (
<Box>
<StyledInput showBorders={showborders ? 1 : 0} value={100} />
</Box>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.