Class组件详解

90 阅读1分钟

创建 Class 组件

ES5 (方式一:过时)

import React from 'react'

const A = React.createClass({
    render() {
        return (
            <div>hi</div>
        )
    }
})

export default A

ES6 (方式二)

import React from 'react'
class App extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>hi</div>
        )
    }
}
export default B;

Props

image.png

  • 外部数据被包装为一个对象
  • {name:'ivan', onClick:..., children:'hi'}
  • 此处的 onClick 是一个回调

初始化

class B extends React.Component {
    constructor(props) {
        super(props);
    }
    render(){}
}
  • 要么不初始化, 即不写 constructor
  • 要么初始化, 且必须写全

效果

  • 这么做了之后, this.props 就是外部数据对象的地址了

读取

class B extends React.Component {
    constructor(props) {
        super(props);
    }
    render(){
        return <div onClick={this.props.onClick}>
            {this.props.name}
            <div>
                {this.props.children}
            </div>
        </div>
    }
}
  • 通过 this.props.xxx 读取

写 Props

改 props 的值 (一个地址)

  • this.props = {/*另一个对象*/}
  • 不要写这样的代码, 没有意义
  • 理由: 既然是外部数据, 就应该由外部更新

改 props 的属性

  • this.props.xxx = 'hi'
  • 不要写这样的代码, 没有意义
  • 理由: 既然是外部数据, 就不应该从内部改值

原则

  • 应该由数据的主人对数据进行更改

componentWillReceiveProps 钩子

  • 了解就好, 现在不推荐使用

Props 的作用

接受外部数据

  • 只能读不能写
  • 外部数据由父组件传递

接受外部函数

  • 在恰当的实际, 调用该函数
  • 该函数一般是父组件的函数

State & setState

初始化 State

class B extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            user: {name: 'ivan', age: 18}
        }
    }
    render(){}
}

读写 State

读用 this.state

  • this.state.xxx.yyy.zzz

写用 this.setState(???, fn)

  • this.setState(newState, fn)
  • 注意 setState 不会立刻改变 this.state, 会在当前代码运行完后, 再去更新 this.state, 从而触发 UI 更新
  • this.setState((state, props)=>newState, fn)

image.png

  • 这种方式的 state 反而更易于理解
  • fn 会在写入成功后执行

写时会 shallow merge

  • setState 会自动将新 state 与旧 state 进行一级合并