React 自學筆記2

一、 Props

1. props vs state

props                                                         state

props get passed to the component          state is managed within the component

function parameters                                  variables declared in the function body

props are immutable                                 state can be changed

props - functional components                  useState Hook - functional components

this.props - class components                   this.state - class components

注意:react 只允許返回一個元素。

2. state

1). 不要直接更改state的值,而是使用setState方法來改state的值。

如: // 錯誤示範:直接更改state的值

increment(){

        this.state.count = this.state.count + 1

        console.log(this.state.count)

}

// 結果導致頁面上的count值并沒有改變,僅僅改了後臺的值(見下面的截圖) 

如:// 正確的更改state值的做法,使用setState方法

increment(){

        this.setState({

            count: this.state.count + 1

        })

}

// 結果,頁面上的count值如願改變了 (如下圖)

     

2)若是同步的console.log()打印出的數值會滯後。所以,需要使用異步打印,setState方法有callback function可以使用。

3)當必须根据以前的state值来更新state时,可以傳入一個函数作为参数,而不是傳入常规的对象。

二、Event Handling

1. 四種綁定this的方法

1)在render中使用bind

如:render() {

    return (

      <div>

          <div>{this.state.message}</div>

          <button onClick = {this.clickHandler.bind(this)}>Click</button>

      </div>

    )

  }

2)在render中使用arrow function

如:render() {

    return (

      <div>

          <div>{this.state.message}</div>

          <<button onClick = {() => this.clickHandler()}>Click</button>

      </div>

    )

  }

3)直接在類構造器中使用bind方法(比較常用,推薦)

如:this.clickHandler = this.clickHandler.bind(this)

render() {

    return (

      <div>

          <div>{this.state.message}</div>

          <button onClick = {this.clickHandler}>Click</button>

      </div>

    )

  }

4)類似添加屬性,在arrow function中綁定(推薦)

如:clickHandler = () => {

        this.setState({

            message: 'Goodbye.'

        })

    }

render() {

    return (

      <div>

          <div>{this.state.message}</div>

          <button onClick = {this.clickHandler}>Click</button>

      </div>

    )

  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值