简体   繁体   中英

Passing Children Styling Down to a Styled Component

I am making a generalized version of a styled component to replace duplicated code in my codebase. The component looks something like this:

const CustomDiv = styled.div`
  display:flex;
  b {
     padding-right:5px
   }
`;

const DivWrapper = ({style, children}) => {
  return (
    <CustomDiv style={style}>
      {children}
    </CustomDiv>
  );
};

I want to be use this "DivWrapper" in other places of the code base but be able to change the b padding in other places when using it. I tried extending it like this:

const SuperCustomDiv = styled(CustomDiv)`
  b {
    padding-right:10px
  }
`;

I am using the styled components library for React.

You can achieve this by using css props and passing props from the styled-component to the CSS. So, we create styled CSS with some property, then this style place to both styled components. With props, we will pass the value to main style.

import styled, { css } from "styled-components";

const PaddingStyle = (value) => css`
  padding-right: ${value}px;
`;

export const SuperCustomDiv = styled.b`
  ${PaddingStyle((props) => props.padding)}
`;

export const CustomDiv = styled.div`
  display: flex;
  b {
    ${PaddingStyle((props) => props.padding)}
  }
`;

export const DivWrapper = ({ padding = 50, children }) => {
  return (
    <CustomDiv as="div" padding={padding}>
      <b>Name:</b> {children}
    </CustomDiv>
  );
};

export default function App() {
  return (
    <div className="App">
      <DivWrapper>John Doe</DivWrapper>
      <SuperCustomDiv padding={30}>Super</SuperCustomDiv>
      <span>John Smith</span>
    </div>
  );
}

编辑令人眼花缭乱的代码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM