如何设置嵌套元素的样式以与样式组件react?

IT技术 css reactjs
2021-05-20 05:44:51

我正在使用样式组件,并希望通过嵌套的 css 在 div 内设置子项样式。在这里查看我的演示

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    ">span": {
      background: "red"
    }
  }
});

function TypographyTheme(props) {
  return (
    <div className={props.classes.root}>
      <h1>
        <span>{"This div's text looks like that of a button."}</span>
      </h1>
    </div>
  );
}
1个回答

它看起来像 JSS 语法,而不是样式组件。

改变这个:

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    ">span": {
      background: "red"
    }
  }
});

有了这个:

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    "& span": {
      background: "red"
    }
  }
});

或者如果你不想改变所有嵌套的跨度

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    "& > h1 > span": {
      background: "red"
    }
  }
});

试试这个codesandbox https://codesandbox.io/s/vm3qnmj75l

供参考:http : //cssinjs.org/jss-nested/