【问题标题】:Is there a way to target a nested JSS styled component within another JSS styled component? [JSS-nested/Styled-JSS/Material UI (React)]有没有办法在另一个 JSS 样式的组件中定位嵌套的 JSS 样式的组件? [JSS-nested/Styled-JSS/Material UI (React)]
【发布时间】:2021-05-09 08:11:52
【问题描述】:

是否可以以样式组件允许的类似方式在另一个样式 JSS 对象中定位样式 JSS 对象?

以下是我所说的样式化组件的示例:

const Child = styled.div`
  color: red;
`;

const Parent = styled.div`
  display: flex;
  ${Child}:hover {
    color: blue
  }
`;

这在 JSS 中可行吗?

仅供参考,我正在使用基于 JSS 的 Material UI v4 样式解决方案。

【问题讨论】:

  • 我可能弄错了,但我认为您不能将反引号与 MUI 的样式 api 一起使用
  • @Barryman9000 我给出的代码示例不是用 JSS/MUI 的样式化 api 编写的。它使用样式化组件来说明我想用 JSS/MUI 的样式化 api 完成什么。

标签: reactjs material-ui styled-components jss css-in-js


【解决方案1】:

您可以将您的子组件传递给父组件的样式化 API。

const Child = styled("div")({
  color: '#fff'
});
const Parent = styled(Child)({
  background: '#999'
})

更新

是的,我误会了。我认为您不能仅使用 MUI styled API 来做到这一点?我能得到的最接近的是使用 className 道具(或者您可以在 MUI 组件上使用 classes 道具)

const Parent = styled('div')({
  background: '#999',
  '& .warning': {
    '&:hover': {
      color: 'goldenrod'
    }
  },
  '& .error': {
    '&:hover': {
      color: 'red'
    }
  }
})

<Parent>
  <Child className="warning">Warning!</Child>
  <Child className="error">Error!</Child>
</Parent>

【讨论】:

  • 感谢您的建议,但我正在寻找一种方法来定位可在“父级”中找到的“子级”嵌套实例。除非我遗漏了什么,否则您给出的示例似乎是创建一个名为“Parent”的“Child”样式版本。
【解决方案2】:

在 JSS 中使用 & 和括号以及括号 [] 来实现:

const Child = styled(div)({
  color: 'red',
});

const Parent = styled(div)({
  display: 'flex',
  [`& ${Child}:hover`]: {
    color: 'blue'
  }
});

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 2019-04-23
    • 2018-09-12
    • 2021-10-10
    • 1970-01-01
    • 2020-10-12
    • 2020-11-03
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多