十二、React中使用CSS

86 阅读1分钟
  • 内联书写
  • 普通导入(全局)
  • cssModule <App.module.css>
  • all in JS
  • classNames
import React, { PureComponent } from "react";
import { AppWrapper } from "./style";

export class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      mainColor: "yellow",
    };
  }
  render() {
    let { mainColor } = this.state;
    return (
      <AppWrapper mainColor={mainColor}>
        <div className="container">
          <h2 className="title">标题内容</h2>
          <main className="main">主体内容</main>
          <div className="footer">
            <div className="left">底部左侧</div>
            <div className="right">底部右侧</div>
          </div>
        </div>
      </AppWrapper>
    );
  }
}

export default App;

js

import styled from 'styled-components'

// 可以接受外部传入的变量  props
export const AppWrapper = styled.div`
  .container {

  }
  .title {
    color: #fff;
    background: rgba(0,0,0,.6);
    margin: 0;
    padding: 0;
    text-align: center;
  }
  // 可以接受外部传入的变量  props
  .main {
    height: 200px;
    width: 100%;
    background-color: skyblue;
    color: ${props => props.mainColor}; // 接收一个函数
  }
  .footer {
    display: flex;
    justify-content: space-between;
    background-color: orange;
    .left {
      width: 300px;
    }
    .right {
      flex: 1;
    }
  }
`

classNames

```
<h2 className={classNames('a', {active: isActive})}></h2>
```