[英]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 应用程序,并且我有一个组件“导航”。 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.先感谢您。
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 */
`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.