【问题标题】:Styled Components - use styled component as base for another component样式化组件 - 使用样式化组件作为另一个组件的基础
【发布时间】:2021-08-16 20:14:55
【问题描述】:

我认为这可以通过样式化组件实现

使用第一个样式组件 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'));

有没有办法做到这一点

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    是的,比如this

    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;
    `
    

    否则没有任何作用。

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 2020-09-26
      • 2020-09-22
      • 2021-07-02
      • 2020-10-27
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多