首页 > 解决方案 > 将对象作为道具传递 - 可重用的下拉组件

问题描述

我正在创建一个可重用的 Dropdown 组件,并且我想通过一个对象进行映射,该对象将传递给组件,如下所示:

const dropdownitems = [
  { name: 'Menu Item 1', action: '/menuitem1' },
  { name: 'Menu Item 2', action: '/menuitem1' }
]

// Reusable component
<Options getdata="dropdownitems" icon="notifications" />

我很难弄清楚我们应该如何将其作为 .map 中的道具传递:

...
{props.getdata.map(({name, action}) => (
  <TextLink href={action} text={name} />
))}
...

这当然是返回: Cannot read property 'map' of undefined

编辑:更正了对象(我的错误)。这就是我在代码中实际使用它的方式。

希望这是有道理的。
感谢您的关注!

标签: reactjs

解决方案


const notifications = []; /* some kind of data */
const items = [
  { name: 'Menu Item 1', action: '/menuitem1' },
  { name: 'Menu Item 2', action: '/menuitem1' }
]

// Reusable component
<Options getdata={items} icon={notifications} />

“getdata”也是一个非描述性名称;我建议使用“数据”或“项目”或“选项”...

并重命名:

<Options options={items} icon={notifications} />

在子组件中:

...

{props.options.map((el) =>{ /* code here */})}
...


推荐阅读