在React中通过map方法传递prop

我需要映射通过数组以输出一堆组件。

我遇到的困难是通过一个函数作为道具-它看起来像这样:

const myFunction = () => {
console.log("Got a click!")
}

const components = myArray.map(arrayItem => {
return <MyComponent clickHandler={myFunction}/>
});

...但是我无法从地图访问myFunction。我知道我可以使用上下文,但是如何用道具来实现呢?

评论
  • comnis
    comnis 回复
    const myFunction1 = () => {
    console.log("Got a click!")
    }
    
    const myFunction2 = () => {
    console.log("Got a click!")
    }
    
    const myArray = [myFunction1, myFunction2];
    
    const components = myArray.map(arrayItem => {
        return <MyComponent clickHandler={arrayItem}/>
    });
    

    You have an array of functions and you want to add clickhandlers for your components where you make use of these functions, and these React components are stored in the new array components. is this what you are trying to do?

  • 死一般的静
    死一般的静 回复

    用合成事件“ onClick”替换clickHandler。

    https://reactjs.org/docs/events.html#mouse-events