React事件绑定的方法
前言
React事件绑定即将事件函数中的this
与类实例对象的this
绑定。
法一:在构造器中绑定this
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>
)
}
}
法二:使用箭头函数
export default class Test extends Component {
handleClick=()=>{
console.log('点击了',this)
}
render(){
return (
<div onClick={
this.handleClick }>click btn</div>
)
}
}
法三:用箭头函数包裹起来
export default class Test extends Component {
handleClick(){
console.log('点击了',this)
}
render(){
return (
<div onClick={
()=> this.handleClick() }>click btn</div>
)
}
}