【问题标题】:Passing prop via map method in React在 React 中通过 map 方法传递 prop
【发布时间】:2020-05-23 11:41:08
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • “我无法从地图访问 myFunction”是什么意思?
  • 如果myFunction 在范围内,那么您可以在.map 中正常使用它。请提供更多上下文

标签: javascript reactjs


【解决方案1】:
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}/>
});

【讨论】:

  • 在 OP 的问题中 myArrayarrayItem 与道具或传递的函数没有任何关系。 OP 的代码目前没有任何问题,他们应该提供更多信息。
  • 他的代码可能没有语法问题,但我猜他正在尝试实现与我的答案类似的东西。
  • 当然,但这是一个假设。在 OP 更新他们的问题之前,我们永远不会知道
猜你喜欢
  • 2018-04-26
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2022-01-24
  • 2021-08-26
  • 1970-01-01
相关资源
最近更新 更多