React + 样式化组件:我应该完全避免使用 CSS 文件吗?

IT技术 reactjs styled-components
2021-05-25 07:15:05

我有一个由许多样式组件组成的大型“主页”组件。到现在为止还挺好。

但是,我现在注意到我需要一些简单的 div,它们只需要它们的位置样式。我的问题是:我需要为那些 div 制作组件吗?我需要的唯一属性是position: relative;.

    <div> <------ I need this to have position: relative, How?
      <Countdown> <------  I need this to have top: -150px, which I did using styled-components.
        <Text>COUNTDOWN</Text>
      </Countdown>
    </div>

所以我认为样式组件的想法是完全避免类名?遇到这种情况我该怎么办?感觉如果我必须从绝对所有的东西中制作一个组件,那将是组件矫枉过正。

另外,我不知道是否top: -150px属于 Countdown ......将定位样式作为组件默认样式的一部分很奇怪,因为这使得它的可重用性大大降低。

1个回答

我在 github 页面上问过,显然我应该制作一个新的布局组件,即使它是一次性的。https://github.com/styled-components/styled-components/issues/1588

只需将其设置为组件本地,不要导出它。

这是一个例子。

import React from "react";
import styled from "styled-components";
import IMAGES from "assets/images";
import Step from "views/homepage/step";

const Wrapper = styled.div`
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 0 10%;
  height: 350px;
`;

const Icon = styled.img.attrs({
  src: props => props.src
})`
  width: 130px;
`;

const Arrow = styled.img.attrs({
  src: props => props.src
})`
  width: 20%;
  margin-bottom: 100px;
`;

const Title = styled.p`
  color: #3b24c2;
  font-size: 13px;
  font-weight: bold;
  text-align: center;
`;

const Description = styled.p`
  color: black;
  font-size: 13px;
  text-align: center;
`;

const Instructions = () => (
  <Wrapper>
    <Step>
      <Icon src={IMAGES.HOW_IT_WORKS_1} />
      <Title>STEP 1: CREATE ACCOUNT</Title>
      <Description>
        Plusieurs variations de Lorem Ipsum peuvent être trouvées ici
      </Description>
    </Step>
    <Arrow src={IMAGES.HOW_IT_WORKS_ARROW_1} />
    <Step>
      <Icon src={IMAGES.HOW_IT_WORKS_2} />
      <Title>STEP 2: DESIGN PAGE</Title>
      <Description>
        Plusieurs variations de Lorem Ipsum peuvent être trouvées ici
      </Description>
    </Step>
    <Arrow src={IMAGES.HOW_IT_WORKS_ARROW_2} />
    <Step>
      <Icon src={IMAGES.HOW_IT_WORKS_3} />
      <Title>STEP 3: PUBLISH PAGE</Title>
      <Description>
        Plusieurs variations de Lorem Ipsum peuvent être trouvées ici
      </Description>
    </Step>
  </Wrapper>
);

export default Instructions;

因此,如果我们在此示例中不使用样式组件,我基本上将不得不在 CSS 文件 + 在一堆元素上添加 className 之间来回切换。这样更简洁,开始理解为什么它如此受欢迎。