<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="test"></div>
<script type="text/babel">
class Clock extends React.Component{
constructor(props){
super(props)
this.state={
date :new Date().toLocaleTimeString()
}
this.go = this.go.bind(this)
}
go(){
console.log("go",this);
this.setState({
date:new Date().toLocaleTimeString()
})
}
go1=()=>{
console.log("go1",this);
this.setState({
date:new Date().toLocaleTimeString()
})
}
render(){
return (
/*
箭头函数包裹直接调用:this指向其所在的作用域,即render所在作用域,即实例
普通函数包裹 this指向undefined
重新绑定this bind每次都会生成一个新的函数,性能差
一次性绑定:在构造函数中利用bind一次性绑定
最优解:利用箭头函数先包裹住方法go1
*/
<div>
<h1>class中this绑定</h1>
<h1>{this.state.date}</h1>
<button onClick={this.go}>直接调用</button>
<button onClick={()=>{this.go()}}>箭头函数包裹直接调用</button>
<button onClick={function(){
console.log("function",this);
this.go
}}>普通函数包裹直接调用</button>
<button onClick={this.go.bind(this)}>重新绑定</button>
<button onClick={this.go}>一次性绑定</button>
<button onClick={this.go1}>箭头函数声明</button>
</div>
)
}
}
ReactDOM.render(<Clock/>,document.getElementById("test"))
</script>
</body>
</html>
12-09
523
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-08
1496
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-13