简体   繁体   English

材质ui情感/样式如何组合多个css类片段?

[英]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>
  );

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何扩展 css 情感风格的基础组件? - How to extend css emotion styled base components? 类型实例化过深,并且可能是无限的,带有 Emotion 样式 + material-ui + typescript - Type instantiation is excessively deep and possibly infinite with Emotion styled + material-ui + typescript 在多个样式的HoC上具有样式的Material UI withStyles - Material UI withStyles on multiple styled HoCs Styled-components vs Emotion - 如何在 Styled-components 上重新应用 css`style` function - Styled-components vs Emotion - How to reapplicate css`style` function on Styled-components 如何使用材料 ui 中的“样式”反应 - How to use 'styled' from material ui react React:如何组合 Material-UI 中标记的多个样式 - React: How to combine each multiple styles marked in Material-UI 如何在组件中运行材料 UI 示例片段 - How to run material UI example snippets within a component 如何使用类名将常规JSS类与Material-UI的类重写功能结合在一起 - How to combine a regular JSS class with Material-UI's classes override feature using classnames @emotion 使用@material-ui v5 将样式表注入到项目中,但是我自己没有在任何地方定义 CSS 规则 - @emotion injecting stylesheet into project with @material-ui v5, but CSS rule is not defined anywhere by myself 一次定位多个类 Material UI - Target multiple classes at once Material UI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM