There are three ways to bind events in the DOM:
Method 1: DOM0 level event binding
<body>
<button id="btn">点我</button>
<script>
// DOM0级别的事件绑定
let btn = document.getElementById("btn");
btn.onclick = function(){
console.log("点我干啥~");
}
</script>
</body>
Method 2: DOM2 level event binding
<body>
<button id="btn">点我</button>
<script>
// DOM0级别的事件绑定
let btn = document.getElementById("btn");
btn.addEventListener("click",()=>{
console.log("点我干啥~");
})
</script>
</body>
Method 3: HTML-level event binding (brackets must be added after the method)
<body>
<button id="btn" onclick="fn()">点我fn()</button>
<button id="btn" onclick="fn">点我fn</button> 不加() 不OK
<script>
function fn(){
console.log("点我干啥~");
}
</script>
</body>
Event binding in react
In react event processing, this question is very important.
To deal with this problem:
1) The listener can be turned into an arrow function. Without passing parameters, it can be bound like this: onClick={ this._clickHandle}
2) In the constructor (constructor), you can use bind. Binding, binding: onClick={ this._clickHandle} cannot pass parameters
3) Binding onClick={ this._clickHandle.bind(this,1,2)} directly when using the monitor
class MyCom extends Component{
constructor(){
super();
this.state = {
isHot:false
}
// bind返回一个改变了this指向的新函数
this._clickHandle = this._clickHandle.bind(this)
}
render(){
let {
isHot } = this.state
return (
<div>
<h1>今天天气很{
isHot ? "炎热" : "寒冷"}</h1>
{
/* onClick是React中对原生DOM中的onclick又一次封装 */}
{
/* <button onClick={ this._clickHandle }>切换</button> */}
{
/* 这里面的调用的_clickHandle是调用16行的_clickHandle */}
<button onClick={
this._clickHandle }>切换</button>
</div>
)
}
_clickHandle(){
console.log(this);
let {
isHot } = this.state
// 更新状态机
this.setState({
isHot:!isHot
})
}
}
4) Recommended writing: onClick={ (e)=> this._clickHandle(111,222,e)}
class MyCom extends Component{
constructor(){
super();
this.state = {
isHot:false
}
}
render(){
let {
isHot } = this.state
return (
<div>
<h1>今天天气很{
isHot ? "炎热" : "寒冷"}</h1>
<button onClick={
(e)=> this._clickHandle(111,222,e) }>切换</button>
<a href="xxx" onClick={
(e)=> this._clickHandle(111,222,e) }>切换</a>
</div>
)
}
_clickHandle(a,b,e){
console.log(a,b,e);
e.preventDefault(); // 阻止默认事件
console.log(this);
let {
isHot } = this.state
// 更新状态机
this.setState({
isHot:!isHot
})
}
}