React:如何通过名称引用样式组件的子项

React: how to refer to child of styled-component by its name

有没有办法通过名称来引用 styled-component 的子组件?或者,除了传递硬编码的类名并引用它之外,没有其他办法吗?

const Parent = styled.div`
  // some styles

  & > Child1 {
    opacity: 1;
  }

`;

const Child1 = styled.div`
  opacity: 0;
`;

const Child2 = styled.div`
  opacity: 0;
`;


const App = (props: Props) => (
  <Parent>
    <Child1 />
    <Child2 />
  </Parent>
)

嗯,您的样式中缺少 ${}。另外,您可能希望在声明 Child1.

之后放置 const Parent
const Child1 = styled.div`
  opacity: 0;
`;

const Child2 = styled.div`
  opacity: 0;
`;

const Parent = styled.div`
  // some styles

  & > ${Child1} {
    opacity: 1;
  }

`;


const App = (props: Props) => (
  <Parent>
    <Child1 />
    <Child2 />
  </Parent>
)

如果您想了解更多关于 template literals 的信息,请点击此处 link。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals