[英]es6 arrow function, not getting param value in React app
Hi I have been trying to pass values to es6 arrow function in my React app, but not successful so far. 嗨,我一直在尝试将值传递给我的React应用程序中的es6箭头函数,但到目前为止还没有成功。 Here is what I am doing
这是我在做什么
var data = [];
for (var i=1; i<=5; i++) {
data.push(<li><a href="#" onClick={(e) => this.getData(e, i)} >{i}</a></li>);
}
and code for getData is 和getData的代码是
getData (e, page){
e.preventDefault();
//here I am calling an api to get data as per page params
}
but actually when the click happens i get nothing. 但是实际上,当点击发生时,我什么也没得到。 Any help!
任何帮助!
I have tested this code. 我已经测试了这段代码。 It works ok - getData method is invoked when I click a link.
没关系-单击链接时将调用getData方法。
You just need to change var
to let
to get right value of i
param. 你只需要改变
var
来let
得到的权值i
PARAM。
var data = [];
for (let i=1; i<=5; i++) {
data.push(<li><a href="#" onClick={(e) => this.getData(e, i)} >{i}</a></li>);
}
try this: 尝试这个:
var data = [];
for (var i=1; i<=5; i++) {
data.push(<li><a href="#" onClick={this.getData.bind(this, i)}>{i}
</a></li>);
}
Here is a working example: http://jsbin.com/lokafas/edit?html,js,console,output 这是一个工作示例: http : //jsbin.com/lokafas/edit?html,js,console,output
By the way, I also recommend using let
and const
when you use ES6 syntax anyways. 顺便说一句,我还建议您无论如何都要使用ES6语法时使用
let
和const
。
You have to bind this
somewhere in order for your code to work. 您必须
this
绑定this
某个地方才能使代码正常工作。 Best way is to do it in the constructor: 最好的方法是在构造函数中执行此操作:
export default class SomeCoolName extends React.Component {
constructor() {
super();
this.getData = this.getData.bind(this); // this is important!
}
getData(e, page) {
// code
}
// somewhere in the code, in render() maybe
var data = [];
for (var i=1; i<=5; i++) {
data.push(<li><a href="#" onClick={(e) => this.getData(e, i)} >{i}</a></li>);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.