如何在react中设置嵌套元素的样式?

时间:2018-06-25 11:41:30

标签: css reactjs

我正在使用样式化的组件,并希望通过嵌套的CSS在div内为孩子设置样式。观看我的演示here

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 个答案:

答案 0 :(得分:6)

它看起来像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/