React--class组件

创建Class组件

  • ES5
import React from 'react'

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

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

Props外部数据

  • 传入 props给 B 组件
export default class Parent extends React.Component{
  constructor(props){
    super(props)
    this.state = {name:'fanison',n:1}
  }
  onClick = ()=>{
    this.setState((state)=>{
      return {n:state.n + 1}
    })
  }
  render(){
    return <B name={this.state.name} onClick={this.onClick} n={this.state.n}> hi </B>
  }
}

class B extends React.Component{
  constructor(props){
    super(props)      // this.props 就是外部数据对象的地址
  }
  render(){
    return (<div>
        {this.props.children},
        {this.props.name}
        <div>
          {this.props.n}
          <button onClick={this.props.onClick}>+1</button>

        </div>
      </div>
    )
  }
}
  • Props的作用

接受外部数据:只能读不能写,外部数据由父组件传递
接受外部函数:在恰当的时机调用该函数(一般是父组件的函数)

State & setState 内部数据

class   B extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      name: 'fanison',age:18
    }
  }
render(){}
}
  • 读 State
    this.state.name
  • 写State
    this.setState(???,fn)

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

onClick2 = ()=>{
    this.setState({n:this.state.n + 1})
    console.log(this.state.n)        //2
    this.setState({n:this.state.n + 1})
    console.log(this.state.n)       //2
  }

    onClick3 = ()=>{
      this.setState({n:this.state.n + 1},()=>{
        this.setState({
          n:this.state.n + 1
        })
      })
    }

this.setState((state,props)=> newState,fn)

onClick = ()=>{
  this.setState((state)=>{
    return {n:state.n + 1}
  })
  this.setState((state)=>({n:state.n + 1}))
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。