如何使用 styled-components 更改另一个组件中单个组件的样式?

How to change the style of a single component within an other component with styled-components?

我正在使用 styled-components 开发一个 React 应用程序,我有一个组件 'Navigation'。在这个组件中有更多组件,如 , 等。 Header 例如声明如下:

const Header = styled.div` height: 48px; width: 100%; transition: all 0.5s ease-in;

问题是我在不同的文件中有这个导航组件,并且所有这些文件的样式都很好,但现在我想在其中一个文件中更改 Header 组件的背景颜色,这在(?)导航组件内。我怎样才能做到这一点? 我知道可以使用 const NewNav = styled(Navigation)`` 之类的内容更改导航组件的样式,但是 Header?

呢?

提前谢谢你。

您可以 pass props 通过您的导航组件到达您的 header。

<NavigationExample secondary />
import styled, { css } from 'styled-components';

function NavigationExample(props) {
  const { secondary } = props;

  return (
    <Navigation>
      <Header secondary={secondary}>
        ...
      </Header>
      <Profile>
        username
      <Profile>
    </Navigation>
  );
}

const Navigation = styled.nav;

const Header = styled.header`
  /* Base styles */
  width: 100%;
  height: 60px;
  background: #222;
  color: #fff;

  ${props => props.secondary && css`
    background: #fff;
    color: #000;
  `;
`;

const Profile = styled.div``;

export default NavigationExample;

或者,您可以 inline props in your css

<NavigationExample backgroundColor="#222" />
const Header = styled.header`
  /* Base styles */
  width: 100%;
  height: 60px;
  background: ${props => props.backgroundColor || '#222'};
  color: ${props => props.backgroundColor ? '#000' : '#fff'}; /* Adjusting text so it's legible like the previous example */
`;