如何使用样式化的组件更改其他组件中单个组件的样式?

时间:2019-11-30 23:32:03

标签: javascript css reactjs styled-components

我正在使用具有样式组件的React应用程序,并且有一个组件“ Navigation”。在此组件中,还有更多组件,例如,等。 例如,标头声明如下:

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

问题是我在不同文件中都有这个Navigation组件,对于所有文件而言,样式都不错,但现在我只想在其中一个文件中更改Header组件的背景色,该文件位于(?)导航组件。我怎样才能做到这一点? 我知道可以使用 const NewNav = styled(Navigation)``之类的东西从Navigation组件更改样式,但是页眉又如何呢?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以pass props通过导航组件到达标题。

<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 */
`;