首页 > 解决方案 > 带有打字稿的对象循环中的功能自定义组件

问题描述

我想显示来自 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.Elementconst Info = (key: any, value: string): JSX.Element似乎可以修复该错误,但该组件仍然没有呈现。

为什么这不起作用,我怎样才能使它起作用?

标签: reactjstypescript

解决方案


Info不是功能性反应组件,功能性组件仅接收一个参数,即props

你可以用两个选项来修复你的代码

选项1Info用作函数

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>
)

推荐阅读