reactjs - 当组件需要一个对象时,如何将函数作为道具传递?
问题描述
我有以下组件
<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' 类型中是必需的
如何在不必传递整个对象的情况下解决这个问题?
解决方案
如果要传递函数的返回值,则直接调用它。
<Object
dropDownProps={this.generarDropDownListaProductos(empresa.listaProductos)}
/>
要修复类型不匹配,请执行以下操作:
generarDropDownListaProductos = (lista): IButtonDropDownProps => {
return {
items: [{text: "text", title: "title", prices: { new: 100, old: 100}, disabled: false}]
}
}
确保导入IButtonDropDownProps
类型。
推荐阅读
- windows - 在 vscode 终端中运行 octave-cli
- c# - 具有多个类构造函数的 C# Json 反序列化
- javascript - 可恢复块上传
- echarts - 如何使用 ECharts 的格式化程序来指定国际数字格式?
- pyspark - Pyspark从数据框中的整数中删除逗号
- amazon-web-services - 环境变量 ElasticBeanstalk 多容器
- express - 努力正确使用 Axios 异步调用的函数的返回值
- reactjs - 使用 useEffect 和 useState 在查看时增加数字
- python - 从 Pandas 数据类型获取 Python 类型
- iis - 如何使用 IIS 将所有请求重定向到网络服务器上的特定文件夹