reactjs - 带有打字稿的对象循环中的功能自定义组件
问题描述
我想显示来自 javascript 对象的列表props.fields
,其中长度或键是未知的。
这有效:
import React from 'react'
interface Props {
title: string
fields: Field
}
interface Field {
[key: string]: string
}
const InfoPanel = (props: Props): JSX.Element => (
{display(props)}
)
function display(props: Props): Array<JSX.Element> {
const toDisplay = []
Object.keys(props.fields).forEach((key: string) => {
toDisplay.push(
<div>
<div className="info__line">{key}</div>
<div className="info__line">{props.fields[key]}</div>
</div>
)
})
return toDisplay
}
export default InfoPanel
但是,当我尝试display
使用子组件分解函数时,它不再起作用:
import React from 'react'
interface Props {
title: string
fields: Field
}
interface Field {
[key: string]: string
}
const InfoPanel = (props: Props): JSX.Element => (
{display(props)}
)
function display(props: Props): Array<JSX.Element> {
const toDisplay = []
Object.keys(props.fields).forEach((key: string) => {
toDisplay.push(<Info key={key} value={props.fields[key]} />)
})
return toDisplay
}
const Info = (key: string, value: string): JSX.Element => (
<div>
<div className="info__line">{key}</div>
<div className="info__line">{value}</div>
</div>
)
export default InfoPanel
我的代码编辑器返回错误:
Const Info: (key: string, value: string) => JSX.Element
Type '{ key: string; value: string; }' is not assignable to type 'string'
更改const Info = (key: string, value: string): JSX.Element
为const Info = (key: any, value: string): JSX.Element
似乎可以修复该错误,但该组件仍然没有呈现。
为什么这不起作用,我怎样才能使它起作用?
解决方案
Info
不是功能性反应组件,功能性组件仅接收一个参数,即props
你可以用两个选项来修复你的代码
选项1:Info
用作函数
function display(props: Props): Array<JSX.Element> {
const toDisplay = []
Object.keys(props.fields).forEach((key: string) => {
toDisplay.push(Info(key,props.fields[key]))
})
return toDisplay
}
option2将您的组件转换Info
为功能组件
toDisplay.push(<Info title={key} value={props.fields[key]} />)
const Info = (props:any): JSX.Element => (
<div>
<div className="info__line">{props.title}</div>
<div className="info__line">{props.value}</div>
</div>
)
推荐阅读
- powerpoint - 如何检测 power point 文件中的损坏位置?
- appium - UIAutomator 和 UIAutomator2 有什么区别。为什么要切换到 UIAutomator2?
- arrays - 如何在字符串数组中搜索字符串
- mysql - WEEKOFYEAR(NOW()) 与 WEEK('2018-05-1') - 当前日期
- ios - UIPageViewController 和 iMessage 应用程序
- python - 从非常嘈杂的图像Opencv Python中获取矩形形状
- sparql - 使用 SPARQL 获取某个类的超类的第一个实体
- material-ui - Material UI 1.0 中的有条件触发按钮导航
- ios - 没有代码的 Crashlytics 突出显示行
- javascript - 使用 new Date().toLocaleTimeString() 时获取毫秒