首页 > 解决方案 > 当组件需要一个对象时,如何将函数作为道具传递?

问题描述

我有以下组件

<Object 

dropDownProps={{items: [{text: "text", title: "title", prices: { new: 100, old: 100}, disabled: false}]}}
/>

这工作得很好

但我想做以下

创建一个函数,如:

generarDropDownListaProductos = (lista) => {
    //[{text: "text", title: "title", prices: { new: 100, old: 100}, disabled: false}]

    return {items: [{text: "text", title: "title", prices: { new: 100, old: 100}, disabled: false}]}
  }

然后按如下方式传递道具

<Object 

dropDownProps={() => this.generarDropDownListaProductos(empresa.listaProductos)}
/>

但它要求

类型 '() => { items: { text: string; 中缺少属性 'items' 标题:字符串;价格:{新:数字;旧:数字;}; 禁用:布尔值;}[]; }' 但在 'IButtonDropDownProps' 类型中是必需的

如何在不必传递整个对象的情况下解决这个问题?

标签: reactjs

解决方案


如果要传递函数的返回值,则直接调用它。

<Object 
  dropDownProps={this.generarDropDownListaProductos(empresa.listaProductos)}
/>

要修复类型不匹配,请执行以下操作:

generarDropDownListaProductos = (lista): IButtonDropDownProps => {
    return {
     items: [{text: "text", title: "title", prices: { new: 100, old: 100}, disabled: false}]
    }
  }

确保导入IButtonDropDownProps类型。


推荐阅读