不理解的地方:
- 当使用react时,你一般不需要调用addEventListener在DOM元素被创建之后添加事件监听器。相反,只要当元素被初始渲染的时候提供一个监听器就可以了。
- 下面这两种写法的区别:
offClick=()=>{
console.log('点击开关');
this.setState(preState=>({
isToggle: !preState.isToggle
}))
}
offClick=()=>{
console.log('点击开关');
this.setState(preState=>({
isToggle: !preState.isToggle
}))
}
全部代码如下:
import React,{ Component } from 'react';
import { Button } from 'antd';
class DealEvent extends Component {
constructor(props){
super(props);
this.state = {
isToggle: true,
}
}
handleEvent () {
console.log('点击',this);
}
handleClick=(e)=> {
console.log('e',e);
//return false;
e.preventDefault();
}
offClick=()=>{
console.log('点击');
this.setState({
isToggle: !this.state.isToggle,
})
}
offClick=()=>{
console.log('点击开关');
this.setState(preState=>({
isToggle: !preState.isToggle
}))
}
/**
* clickEvent1 函数名
* @param {*} e
* 箭头函数 自动绑定this 这种是显式的 (e,id)e在前 id在后
* 疑问:为什么这两个参数任意的调换位置 打印出的值却不改变???
*/
clickEvent1(id,e) {
console.log('id',id);
console.log('e',e);
console.log('this',this);
}
/**
* clickEvent2 函数名
* @param {*} e
* 箭头函数 这种是隐式的 (this,id)先绑定this,id在后
* 这两个值的位置不能改变,why
*/
clickEvent2(_this,id) {
console.log('this',_this);
console.log('id是',id);
}
render() {
return (
<div>
<h1>Hello,DealEvent1</h1>
<div>
<Button type="primary" onClick={ this.handleEvent }>点击</Button>
</div>
<a href='#' onClick={ this.handleClick }>
点击a标签
</a>
<div onClick={ this.offClick.bind(this) }>
开关
{ this.state.isToggle ? 'NO':'OFF'}
</div>
<Button onClick={(e)=>{ this.clickEvent1(1,e) }}>点击</Button>
<Button onClick={(e)=>{ this.clickEvent2(this,2) }}>点击2</Button>
</div>
)
}
}
export default DealEvent;
3.什么是属性初始化语法?
4.使用箭头函数
import React,{ Component } from 'react';
import { Button } from 'antd';
class DealEvent extends Component {
constructor(props){
super(props);
this.state = {
isToggle: true,
}
}
clickEvent3=(e)=>{
console.log('点击3',e);
}
render() {
return (
<div>
<Button onClick={(e)=> this.clickEvent3(e) }>点击3</Button>
</div>
)
}
}
export default DealEvent;
这种语法的问题是,每次DealEvent渲染时都创建一个不同的回调。在多数情况下没有什么问题。然而这个回调被作为props属性传递给下级组件,这些组件需要额外的重复渲染。我们通常建议在构造函数中绑定,以避免这种性能的问题。
将参数传递给事件处理程序
<Button onClick={(e)=>{ this.clickEvent1(id,e) }}>点击</Button>
<Button onClick={(e)=>{ this.clickEvent2(this,id) }}>点击2</Button>
上面例子中,参数e作为React事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过bind的方式,事件对象以及更多的参数将被隐式的进行传递。