javascript - 在 React 中通过 map 方法传递 prop
问题描述
我需要映射一个数组来输出一堆组件。
我遇到的困难是将函数作为道具传递 - 它看起来像这样:
const myFunction = () => {
console.log("Got a click!")
}
const components = myArray.map(arrayItem => {
return <MyComponent clickHandler={myFunction}/>
});
...但我无法从地图访问 myFunction。我知道我可以使用上下文,但是如何使用道具来实现这一点?
解决方案
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}/>
});
推荐阅读
- docker - 集群中的 Docker 引擎 API
- r - 尝试使用 r 中名称的矢量文件重命名文件夹中的文件
- css - CSS显示无不适用于图像标签
- python - Exec 不适用于函数和变量
- slack-api - 使用 Slack API 故意折叠长消息
- javascript - Video scrubber dragging is being buggy
- python - 从 C++ 调用具有任意数量(编译时未知)参数的 Python 函数
- ios - 关闭打开的应用程序后保留视图控制器模式
- python - TypeError:需要一个类似字节的对象,而不是'str',但类型是'bytes'
- typescript - 打字稿嵌套索引类型