Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - 如何使用样式组件更改其他组件中单个组件的样式?(How to change the style of a single component within an other component with styled-components?)

I'm working on an react app with styled-components and I have a component 'Navigation'.

(我正在使用具有样式组件的React应用程序,并且有一个组件“ Navigation”。)

In this component are more components like , , etc. Header for example is declared like this:

(在此组件中,还有更多组件,如,等。例如,标头声明如下:)

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

Thing is that I have this Navigation component in different files and for all of them the styling is good but now I want to change the background color of the Header component in just one of those files, which is within(?) the Navigation component.

(问题是我在不同文件中都有这个Navigation组件,对于所有文件而言,样式都不错,但是现在我只想在其中一个文件中更改Header组件的背景色,该文件位于Navigation组件之内。)

How can I do that?

(我怎样才能做到这一点?)

I know that it's possible to change the styling from the Navigation component with something like const NewNav = styled(Navigation)`` but what about the Header?

(我知道可以使用const NewNav = styled(Navigation)``之类的东西从Navigation组件更改样式,但是Header呢?)

Thank you in advance.

(先感谢您。)

  ask by Krys translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can pass props through your navigation component to your 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;

Alternatively, you can inline props in your css .

(或者,您可以在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 */
`;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...