【问题标题】:How to style nested elements in react with styled-components?如何设置嵌套元素的样式以与样式组件做出反应?
【发布时间】:2018-12-03 23:32:18
【问题描述】:

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

【问题讨论】:

    标签: css reactjs


    【解决方案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"
        }
      }
    });
    

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

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

    【讨论】:

    • 不会改变所有嵌套的跨度,而不是像 OP 帖子中那样只改变根子节点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2018-07-10
    • 1970-01-01
    • 2021-04-21
    • 2010-10-14
    • 2020-06-28
    • 2015-02-22
    相关资源
    最近更新 更多