React - CSS 引入方式一

1. 组件中引入 [name].css 文件

这种引入方式作用于当前组件和所有后代组件,也可以引入 sass 文件。

import '[name].css'

2. 组件中引入 [name].module.css 文件

这种引入方式仅作用于当前组件,也可以引入 sass 文件。

import React, { Component } from 'react'
import moduleCss from '[name].module.css'

class Test extends Component {
  render() {
    return (
        <h1 className={ moduleCss.title }>标题</h1>
    )
  }
}

3. 使用 style 属性

import React, { Component } from 'react'

const title = {
  fontSize: '30px',
  color: '#000000'
}

class Test extends Component {
  render() {
    <div>
      <h1 style={ title }>标题</h1>
      <p style="color: red;"></p>
    </div>
  }
}

4. 使用 className 属性

import React, { Component } from 'react'

import classNames from 'classnames'  // 导入 classnames 包

class Test extends Component {
  
  constructor() {
    super()
    
    this.handleClick = this.handleClick.bind(this)
    
    this.state = {
      foo: true,
      bar: false
    }
  }
  
  render() {
    
    const h1 = classNames('title', {
      foo: this.state.foo,
      bar: this.state.bar
    })
    
    return (
        <div>
        <h1 className={ h1 }></h1>
        <button onClick={ () => { this.handleClick } }>切换样式</button>
      </div>
    )
    
    handleClick() {
      this.setState({ foo: !this.state.foo, bar: !this.state.bar })
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。