首页 > 解决方案 > 使用 styled-component 修改 css react 组件

问题描述

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

用户界面库

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

我的回购

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

标签: reactjsstyled-components

解决方案


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

只要将传递的 className 属性附加到 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 />
    );
  }
}

推荐阅读