React--class組件

創(chuàng)建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外部數(shù)據(jù)

  • 傳入 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 就是外部數(shù)據(jù)對象的地址
  }
  render(){
    return (<div>
        {this.props.children},
        {this.props.name}
        <div>
          {this.props.n}
          <button onClick={this.props.onClick}>+1</button>

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

接受外部數(shù)據(jù):只能讀不能寫,外部數(shù)據(jù)由父組件傳遞
接受外部函數(shù):在恰當(dāng)?shù)臅r機(jī)調(diào)用該函數(shù)(一般是父組件的函數(shù))

State & setState 內(nèi)部數(shù)據(jù)

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,會在當(dāng)前代碼運(yùn)行完后,再去更新this.state,從而觸發(fā)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}))
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容