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)
小智 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)