Javascript 如何在功能组件中单击React获得childNode索引
请输入下面的代码Javascript 如何在功能组件中单击React获得childNode索引,javascript,reactjs,dom-events,react-functional-component,Javascript,Reactjs,Dom Events,React Functional Component,请输入下面的代码 function getChildIndex(){ //logic here } //render <div> {Array.from({length: 3}).map((item,index) => ( <div onClick={getChildIndex}/> ) )} </div> 函数getChildIndex(){ //这里的逻辑 } //渲染 {Array.f
function getChildIndex(){
//logic here
}
//render
<div>
{Array.from({length: 3}).map((item,index) => (
<div onClick={getChildIndex}/>
)
)}
</div>
函数getChildIndex(){
//这里的逻辑
}
//渲染
{Array.from({length:3}).map((项,索引)=>(
)
)}
它将呈现如下所示
<div>
<div> //with click event // 1st Child
<div> //with click event // 2nd Child
<div> //with click event // 3rd Child
</div>
//单击事件//第一个子项
//单击事件//第二个子项
//单击事件//第三个子项
单击子元素时如何获取子元素编号正如您所示,
索引作为映射的
回调函数的第二个参数可用。只需根据需要使用它,如下所示:-
doSomethingWithIndex(index)}/>
索引作为map的
回调函数的第二个参数可用,如您所示。只需根据需要使用它,如下所示:-
doSomethingWithIndex(index)}/>
这是否回答了您的问题?这回答了你的问题吗?我试着使用上面的方法,但是我得到了一个错误,TypeError:doSomethingWithIndex不是一个函数,我正在将它作为props传递给parents,并将状态提升到parents我希望parents有一个名为doSomethingWithIndex的函数,或者任何你喜欢的函数。很抱歉,你的解决方案是正确的,我没有注意到我忘记在中级组件中传递props,相反,只在最顶层传递我尝试使用上面的方法,但我得到了错误,TypeError:doSomethingWithIndex不是一个函数我将它作为道具传递,并将状态提升到父级我希望父级有一个名为doSomethingWithIndex的函数或任何您喜欢的函数。抱歉,您的解决方案是正确的,我没有注意到我忘了通过中级部分的道具,而是只通过了最高级部分