首页 > 解决方案 > 如何设置嵌套元素的样式以与样式组件做出反应?

问题描述

我正在使用样式化组件,并希望通过嵌套 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>
  );
}

标签: cssreactjs

解决方案


它看起来像 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"
    }
  }
});

试试这个代码框https://codesandbox.io/s/vm3qnmj75l

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


推荐阅读