事件绑定
//DOM0事件绑定
<button>点击</button>
<script>
let btn = document.getElementsByTagName("button")[0];
btn.onclick = function () {
console.log("按钮被点击了~")
}
</script>
//HTML级别的事件绑定
<button onclick="fn()">点击</button>
<script>
function fn() {
console.log("按钮被点击了~")
}
</script>
//DOM2级别的事件绑定
<button>点击</button>
<script>
let btn = document.getElementsByTagName("button")[0];
btn.addEventListener("click",()=>{
console.log("点击了~")
})
</script>
React中解决this丢失
事件绑定
onClick是React中又封装的点击事件和DOM中的onclick不一样
四种方式
1)方式一 this._clickHandle = this._clickHandle.bind(this) 不推荐
2)方式二 <button onClick={this._clickHandle.bind(this)}>切换</button> 不推荐
3)方式三 _clickHandle=()=>{ 不推荐
4)方式四 <button onClick={()=>this._clickHandle()}>切换</button> 推荐
最好的方式:
<button onClick={()=>this._clickHandle(1,2)}>切换</button>
<button onClick={()=>this._clickHandle(3,4)}>切换</button>
包这一层函数目的:1)防止this丢失 2)可以传参
监听器可以写普通的形式,也可以写箭头的形式
方式一
class Weather extends React.Component {
constructor(props) {
super(props);
//定义状态机
this.state = {
isHot: false
}
//方式一:改变click函数中的this指向,返回一个改变后的新函数,挂到this上
this._clickHandle=this._clickHandle.bind(this)
}
render() {
let {isHot} = this.state;
return(
<div>
<h1>天气很{isHot ? "炎热":"凉爽"}</h1>
<button onClick={this._clickHandle}>点击</button>
</div>
)
}
_clickHandle(){
// console.log(this); // 这样写this代表und 我们想让this代表组件对象
let {isHot} = this.state;
//修改状态机
this.setState({
isHot:!isHot
})
}
}
ReactDOM.render(< Weather/>, document.getElementById("root"))
方式二
<button onClick={this._clickHandle.bind(this)}>点击</button>
方式三
箭头函数中没有this
<button onClick={this._clickHandle}>qiehaun</button>
_clickHandle=()=>{
let {isHot} = this.state;
this.setState({
isHot:!isHot
})
}
方式四
<button onClick={e=>this._clickHandle(e)}>
<button onClick={()=>this._clickHandle()}>点击</button>
传参
方式三中单纯的箭头函数不能传参
<button onClick={this._clickHandle}>qiehaun</button>
_clickHandle=()=>{
let {isHot} = this.state;
this.setState({
isHot:!isHot
})
}
因为箭头函数使用时,this._clickHandle使用时不能加(),所以不能传参,不推荐使用。
方式四最推荐
<button onClick={()=>this._clickHandle(1,2)}>点击</button>
外面包一层函数:1、防止this丢失;2、可以传参
下面的函数也可以使用箭头函数。
获取事件对象,传参
<button onClick={(e)=>this._clickHandle(e)}>点击</button>
//可以用箭头函数,也可以不用箭头函数
_clickHandle=(e)=>{
console.log(e);
let {isHot} = this.state;
this.setState({
isHot:!isHot
})
}
<button onClick={e=>this._clickHandle(e,1,2)}>点击</button>
_clickHandle=(e,a,b)=>{
console.log(e,a,b);
let {isHot} = this.state;
this.setState({
isHot:!isHot
})
}
阻止默认事件
DOM中的阻止默认事件:
- 在监听器中return false
- 通过事件对象 e.dexxxx
- href=“javascript:;”
_clickHandle=(e)=>{
e.preventDefault(); // 用来阻止默认事件
let { isHot } = this.state;
this.setState({
isHot:!isHot
})
}