首页 > 解决方案 > 在 React 中通过 map 方法传递 prop

问题描述

我需要映射一个数组来输出一堆组件。

我遇到的困难是将函数作为道具传递 - 它看起来像这样:

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

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

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

标签: javascriptreactjs

解决方案


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

你有一个函数数组,你想为你使用这些函数的组件添加点击处理程序,这些 React 组件存储在新数组components中。这是你想要做的吗?

如果你想传递这个数组(它具有所有这些功能),请通过 props 传递它。

父组件

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

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

const myArray = [myFunction1, myFunction2];

<Child passedArray = {myArray} />

子组件

const myArray = props.passedArray;

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

推荐阅读