点击 ES6 React 获取关键索引

新手上路,请多包涵

我有以下组件

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>
  )
}

单击时,我想获取单击的 li 的索引。使用 ES6 并且没有绑定我怎么能做到这一点?

原文由 Nicc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 605
2 个回答

使用箭头函数。

 onClick={() => handler(index)}

原文由 Radio- 发布,翻译遵循 CC BY-SA 3.0 许可协议

您实际上可以在不使用箭头函数的情况下获取索引。您唯一需要做的就是将索引作为属性传递并从事件中获取该值作为 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>
    );
}

原文由 Salman Momin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进