获取点击ES6 React的关键索引

Nic*_*icc 14 ecmascript-6 reactjs

我有以下组件

const list = (props) => {

  const handler = function(){

  };

  var listItems = props.items.map(function(item, index){
    return (
      <li key={index} onClick={ handler }>
        {item.text}
      </li>
    )
  });

  return (
    <div>
      <ul>
        {listItems}
      </ul>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

点击我想要点击li的索引.使用ES6而不绑定我该怎么办?

Rad*_*io- 23

使用箭头功能.

onClick={() => handler(index)}
Run Code Online (Sandbox Code Playgroud)

  • @Nicc然后更新你的linting规则. (7认同)
  • 这是一种软"坏习惯",因为每次元素渲染它都会创建一个新函数,在某些情况下它可能会导致双重渲染. (4认同)
  • 如果使用eslint插件,建议不要使用箭头功能 (3认同)

小智 12

您实际上可以在不使用箭头函数的情况下获取索引。您唯一需要做的就是将索引作为属性传递并从事件中获取该值作为 e.target.getAttribute("your_attribute_name")

const list = (props) => {

const handler = function(e){
    console.log(e.target.getAttribute("data-index")); //will log the index of the clicked item
};

var listItems = props.items.map(function(item, index){
    return (
    <li key={index} data-index={index} onClick={ handler }>
        {item.text}
    </li>
    )
});

return (
    <div>
        <ul>
            {listItems}
        </ul>
    </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么这比上面接受的答案更好? (2认同)
  • 来自 google 的 @Hamund 引文“如果您在 render 中使用箭头函数,则每次调用 render 都会创建新的函数对象。如果您随后通过 props 将这些函数传递给子元素,基于 PureComponent 或 shouldComponentUpdate 的优化将失败(因为箭头函数 props每次渲染都会改变)。” - 因此,如果您注重性能,那么最好将引用传递给函数而不是箭头函数。 (2认同)
  • 更改为“当前目标” (2认同)