Reactイベントバインディングメソッド
序文
Reactイベントバインディングは、イベント関数をthis
クラスインスタンスオブジェクトにバインドすることthis
です。
方法1:これをコンストラクターでバインドする
export default class Test extends Component {
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
console.log('点击了',this)
}
render(){
return (
<div onClick={
this.handleClick }>click btn</div>
)
}
}
方法2:矢印関数を使用する
export default class Test extends Component {
handleClick=()=>{
console.log('点击了',this)
}
render(){
return (
<div onClick={
this.handleClick }>click btn</div>
)
}
}
方法3:矢印関数でラップする
export default class Test extends Component {
handleClick(){
console.log('点击了',this)
}
render(){
return (
<div onClick={
()=> this.handleClick() }>click btn</div>
)
}
}