首页 > 解决方案 > 样式化组件 - 使用样式化组件作为另一个组件的基础

问题描述

我认为这对于样式化的组件是可能的

使用第一个样式组件Block作为另一个组件的基础,例如

export const BlockOne = styled.Block

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import styled from 'styled-components'

export const Block = styled.div`
  width: 100px;
  height: 100px;
  background: red;
`

export const BlockOne = styled.Block`
  background: yellow;
`

const App = () => {
  return (
    <div>
      <Block/>
      <BlockOne/>
    </div>
  );
}

render(<App />, document.getElementById('root'));

有没有办法做到这一点

标签: reactjsstyled-components

解决方案


是的,像这样

export const BlockOne = styled(Block)`
  background: yellow;
`

styled-component 仅具有基本组件(例如 div、span 等标签)作为属性。对于其他任何事情,您将其作为道具传递。

如果您将自定义组件传递给它,请确保它接受 className 并将其传递给 div 或其他东西:

const MyComponent = ({className}) => {
  return <div className={className}></div> // styled-component will use this classname to apply the style
}

export const MyStyledComponent = styled(MyComponent)`
  background: yellow;
`

否则它不会有任何影响。


推荐阅读