How to trigger 'this' within a loop in React

落花浮王杯 提交于 2019-12-06 07:40:46

javascript map actually has functionality for what you're trying to do. you pass this to the second argument of map (after the callback):

{Object.keys(radios).map(function(key) {
  return ( 
    <div key={key}>
      <label forHTML={key}>
        <input type="radio" name="loopTest" value={radios[key].radio} id={key} onChange={this.selectHandlerLoop} /> {radios[key].radio}
      </label>
    </div>
  );
}, this)}

Your problem has nothing to do with React. You seem to have a misunderstanding of how functions / closures work.

Lets look at that part:

Object.keys(radios).map(function(key,r) { ... });

This declares a function expecting two arguments, key and r, and passes it to .map. .map will call the function and provide the corresponding arguments.

If you look at the .map documentation you can see that .map passes three arguments to the callback:

callback

Function that produces an element of the new Array, taking three arguments:

  • currentValue: The current element being processed in the array.
  • index: The index of the current element being processed in the array.
  • array: The array map was called upon.

So what will the value of r be? It will be the index of the current element.

The parameter r has nothing to do with the variable r you declared with

var r = this;

If you want r inside the callback to refer to that variable, remove it from the parameter list

Object.keys(radios).map(function(key) { ... });
//                                  ^ no r

r is now a free variable inside the callback and will be looked up in higher scopes.

To learn more about closures, have a look at this MDN article.


We can simplify the mapping by using ES6 arrow functions, which you can use if you transpile your code with Babel or jsx --harmony:

{Object.keys(radios).map(key => 
  <div key={key}>
    <label forHTML={key}>
      <input ... nChange={this.selectHandlerLoop} /> {radios[key].radio}
    </label>
  </div>
)}

Because this inside arrow functions is lexically scoped, it will refer to the this value of the render method, which is your React component.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!