项目场景:前端点击下载附件
使用某一个特定button按钮 Button onClick={this.handleDownload("stations")} 点击任意button,handleDownload函数会无条件被触发,都会导致无限制下载。学习React中点击事件传参
问题描述:
使用某一个特定button按钮 Button onClick={this.handleDownload("stations")} 点击任意button,都会无条件触发下载。handleDownload=(mode)=>{
//操作
}
<Button onClick={this.handleDownload("stations")}>
原因分析:
问题分析:
onClick的参数必须是一个函数。()=>{ } 定义了一个匿名函数
在ES6中,匿名函数包括了箭头函数和普通匿名函数。
解决方案:
(1)ES6箭头函数
- 没参数
//被触发函数写法:
handleDownload=()=>{
//操作
}
//被调用时:
onClick={this.handleDownload}
- 有参数
//被触发函数写法:
handleDownload=(mode)=>{
//操作
}
//被调用时 应该:
onClick={(e)=>{this.handleDownload("modeOptions")}
//能运行的写法:
<Button onClick={()=>{this.handleDownload("stations") }>
这个e到底需不需要还不太清楚。
(2)bind函数绑定this
//被触发函数写法:
handleDownload=function()=>{
//操作
}
- 将被触发函数在构造函数中,将当前组件(类)的实例与触发函数进行绑定
constructor(){
this.handleDownload = this.handleDownloa(this);
}
- 在方法调用时绑定this
- 没有参数
onClick={this.handleDownload.bind(this)}
- 有参数
//被触发函数写法:
handleDownload=function(mode,event)=>{
//操作
}
or
handleDownload=function(mode)=>{
//操作
}
传值调用:
```bash
onClick={this.handleDownload.bind(this,mode)}
参考和学习了
https://blog.youkuaiyun.com/genius_yym/article/details/54135567
https://www.jianshu.com/p/004b7f8452af
https://blog.youkuaiyun.com/weixin_34209406/article/details/93860496?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-1.no_search_link&spm=1001.2101.3001.4242
(但对e有疑问)