【问题标题】:Modify css react component with styled-component使用 styled-component 修改 css react 组件
【发布时间】:2019-05-11 21:25:08
【问题描述】:

我正在使用库中的一些组件,这些组件不在我的项目存储库中。因为我使用styled-component 来开发我自己的组件。我想对从其他库中使用的组件进行少量修改,而无需触及那里的代码库。这是我想要实现的目标的一个小例子,但以下风格都没有应用于CustomCom

用户界面库

const CustomCom = ()=>{
  return (
    <div>Child</div>
  );
}

我的回购

export default styled(CustomCom)`
  height: 20px;
  background: green;
`;

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    这只有在组件将 className 传递给 DOM 元素时才有可能,根据 styled-components 文档

    styled 方法完美适用于您自己或任何 第三方组件,只要附上传递的className prop 到 DOM 元素。

    https://www.styled-components.com/docs/basics#styling-any-components

    这是一些示例代码,它当然会修改库代码,我知道你不能这样做,但你可以分叉库并根据需要进行。

    const CustomCom = ({className})=>{
      return (
        <div className={className}>Child</div>
      );
    }
    
    class App extends Component {
      render() {
        const MyElem = styled(CustomCom)`
          height: 20px;
          background: green;
        `
        return (
          <MyElem />
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      试试下面

      export const newCustom  = styled(CustomCom)`
      height: 20px;
      background: green;
      `;
      

      现在使用这个自定义组件

      <newCustom   />
      

      如果你想扩展现有的 HTML 标签,你可以这样做:

      export const newCustom  = styled.div`
      height: 20px;
      background: green;
      `;
      

      【讨论】:

      • 这正是他们在问题中的代码,并不能解决他们遇到的问题,即在不传递 className 的第 3 方组件上使用 styled-components
      猜你喜欢
      • 1970-01-01
      • 2020-06-09
      • 2018-07-03
      • 2021-03-07
      • 2021-08-07
      • 2019-07-28
      • 2020-03-19
      • 2022-11-29
      • 2020-11-20
      相关资源
      最近更新 更多