【问题标题】:How to change the style of a single component within an other component with styled-components?如何使用 styled-components 更改其他组件中单个组件的样式?
【发布时间】:2020-03-26 00:31:41
【问题描述】:

我正在开发一个带有样式组件的反应应用程序,并且我有一个组件“导航”。在这个组件中有更多的组件,例如 , 等。 例如,标头声明如下:

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

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

提前谢谢你。

【问题讨论】:

  • 您应该将您的Header 定义为一个单独的组件并将该组件导入您的Navigation 组件不是吗
  • 这真的是人们常做的事吗?我发现导入 8 个“子”组件只是为了让我的导航组件出现在配置文件中,例如

标签: javascript css reactjs styled-components


【解决方案1】:

你可以通过你的导航组件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 */
`;

【讨论】:

  • 谢谢。我不知道我也可以反过来传递道具。对我来说效果很好。
猜你喜欢
  • 2022-01-07
  • 2021-09-02
  • 1970-01-01
  • 2018-02-01
  • 2018-02-13
  • 2021-06-02
  • 2021-09-19
  • 1970-01-01
  • 2020-01-24
相关资源
最近更新 更多