如何使用 Styled Components 将 className 添加到现有组件

How to use Styled Components to add className to an existing component

我已经通过 Material-ui 的 {withStyle} 属性 了解了如何使用 JSS 的基础知识。我刚刚遇到 'styled-components',我正在尝试学习它的基础知识。但是我找不到关于如何使用样式化组件创建 "classNames" 的文档。请查看下面的代码片段,了解我正在尝试使用 JSS 做什么,你能帮我看看如何处理样式组件部分吗

// WITH JSS======

import React, { Component } from 'react';
import { withStyles } from '@material-ui/core';

const myStyle = {
  container : {
      backgroundColor : "blue"
  }
}

function MySampleComponent = ({classes}) => {
     return(<div>
              <div className={classes.container}> This one is styled 
              </div>
              <div> This one is not </div>
            </div>
        )
}

export default MySampleComponent;


//Now with 'Styled-Components'. 
//I know how to create a .div element with the given styles but I don't know how to name them so that I can use that variable to assign a className for only one of the divs.

const myStyledDiv = styled.div` background-color : blue; `

如何使用变量名 'myStyledDiv' 并将其分配给示例中的第一个 div。

样式化组件有不同的方法。
您不应将 myStyledDiv 视为变量,而应将其视为具有自定义样式的组件。
来自样式组件文档:

styled-components removes the mapping between components and styles. This means that when you're defining your styles, you're actually creating a normal React component, that has your styles attached to it.

因此,在使用 styled-components 时,您无需声明 'myStyledDiv' 变量并将其分配给 div 类名。
您创建一个 'MyStyledDiv' 组件(这是一个具有自定义样式的 div),并以这种方式使用它:

import styled from 'styled-components'

const MyStyledDiv = styled.div`
    background-color: blue;
`;

function MySampleComponent = (props) => {
     return(<div>
              <MyStyledDiv> 
                 This one is styled 
              </MyStyledDiv>
              <div>
                 This one is not 
              </div>
            </div>
        )
}