以下列為例,.bind(),它是用來傳值給goClick()
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : 0
}
goClick(e){
this.setState({
gonum : this.state.gonum+1
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick.bind(this)}>YES</button>
</div>
)
}
}
使用生命週期來定義他,這個方式比較麻煩
import React, { Component } from 'react'
export default class App2 extends Component {
constructor(props) {
super(props);
this.goClick = this.goClick.bind(this);
}
state = {
gonum : 0
}
goClick(e){
this.setState({
gonum : this.state.gonum+1
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick}>YES</button>
</div>
)
}
}
使用箭頭函數來傳值,這個方式寫起來比較方便
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : 0
}
goClick(e){
this.setState({
gonum : this.state.gonum+1
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={()=>this.goClick}>YES</button>
</div>
)
}
}
將goClick()寫成箭頭函數,這樣一樣沒問題,就看習慣哪個方式
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : 0
}
goClick=(e)=>{
this.setState({
gonum : this.state.gonum+1
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick}>YES</button>
</div>
)
}
}