【问题标题】:Styling react component in styled components样式化组件中的样式化反应组件
【发布时间】:2020-10-27 00:09:25
【问题描述】:

我有一个关于样式化组件的问题,我想知道如何定位它们父母的元素,我看到有以下选项,但我不喜欢任何选项。

  • 通过 props,我不喜欢这种方法,因为我认为这种方法的可维护性很糟糕,因为在复杂的情况下我们会有很多 props。
  • 通过className,通常在样式化的组件中我们没有类,因为我们创建了styled.div,例如,我喜欢在我的结构中保持一致性,我不想在一些有类名,而在另一些没有。

在这种情况下 CurrentFinderLocationButton 是一个反应组件,你会如何定位它们?有没有办法在没有 className 或 props 的情况下选择它并从 StyledHome 应用样式?

import React from "react";
import styled from "styled-components";

import CurrentLocationFinderButton from "../buttons/CurrentLocationFinderButton";
import fullLogotype from "../../assets/images/full-logotype.svg";

const Home = () => {
  return (
    <StyledHome>
      <StyledLogotype src={fullLogotype} />
      <CurrentLocationFinderButton />
    </StyledHome>
  );
};

const StyledHome = styled.div`

`;

const StyledLogotype = styled.img`
  width: 150px;
  display: block;
  margin: auto;
`;

export default Home;

【问题讨论】:

    标签: javascript html reactjs styled-components


    【解决方案1】:

    你可以在包装器中添加一些样式

    const StyledCurrentLocationFinderButton = styled(CurrentLocationFinderButton)`
     {any styles}
    `
    

    【讨论】:

    • 这对我不起作用,因为它是一个自定义组件。我实际上正在寻找类似的解决方案,但它不起作用,因为我没有通过 className。
    【解决方案2】:

    最后我解决了这个通过props绑定组件类和样式化组件类的问题。

    import React from "react";
    import styled from "styled-components";
    import fullLogotype from "../../assets/images/full-logotype.svg";
    import CurrentLocationFinderButton from "../buttons/CurrentLocationFinderButton";
    import AddressFinder from "../finders/AddressFinder";
    
    const Logotype = ({ className }) => {
      return <img className={className} alt="" src={fullLogotype} />;
    };
    
    const EntryText = ({ className }) => {
      return (
        <p className={className}>
          Atisbalo es una app donde podrás encontrar información sobre tus locales
          favoritos y enterarte de todas las promociones que oferta tu cuidad al
          instante
        </p>
      );
    };
    const Home = ({ className }) => {
      return (
        <StyledHome className={className}>
          <StyledLogotype />
          <StyleEntryText />
          <StyledCurrentLocationFinderButton />
          <StyledAddressFinder/>
        </StyledHome>
      );
    };
    
    const StyledHome = styled.div``;
    
    const StyledLogotype = styled(Logotype)`
      width: 150px;
      display: block;
      margin: auto auto 30px auto;
    `;
    
    const StyleEntryText = styled(EntryText)`
      display: block;
      width: 90%;
      text-align: center;
      margin: auto auto 30px auto;
    `;
    
    const StyledCurrentLocationFinderButton = styled(CurrentLocationFinderButton)`
      display: block;
      margin: auto auto 30px auto;
    `;
    
    const StyledAddressFinder = styled(AddressFinder)`
      width: 80%;
      margin: auto;
    `
    export default Home;
    

    【讨论】: