【问题标题】:How to map in a React Element?如何在 React 元素中映射?
【发布时间】:2021-07-21 03:04:21
【问题描述】:

我的参数是一个对象数组。我尝试实现它,但出现错误。

参数 'option' 隐含一个 'any' type.ts(7006)

我不知道为什么。感谢您的帮助。

const options = [
  {label: 'one', name: 'one'},
  {label: 'two', name: 'two'},
]

<Checkbox options={options} />

import React from 'react'
import {Checkbox as Cb} from '@material-ui/core'
import {Field, FieldAttributes, useField} from 'formik'

interface CheckboxRecord {
  label: string
  name: string
}

interface Props {
  options: CheckboxRecord[]
}

const Checkbox: React.FC<Props> = options => {
  return options.map(option => <Field name={option.name} as={Cb} />)
}

export default Checkbox

【问题讨论】:

    标签: reactjs typescript create-react-app


    【解决方案1】:

    React 组件的属性是参数中的对象的属性。你的options在这里:

    const Checkbox: React.FC<Props> = options => {
    

    不是你从上面传下来的选项,而是整个道具对象。

    使用

    const Checkbox: React.FC<Props> = ({ options }) => {
    

    或者

    const Checkbox = ({ options }: { options: CheckboxRecord[] }) => {
    

    【讨论】:

    • 是的,我知道。我试过那个版本,但它说:类型'({选项}:PropsWithChildren)=>元素[]'不可分配给类型'FC'。类型 'Element[]' 缺少来自类型 'ReactElement' 的以下属性:type、props、keyts(2322
    【解决方案2】:

    解决方案是: 使用 React.Fragment

    const Checkbox: React.FC<Props> = ({options}) => {
      return (
        <React.Fragment>
          {options.map((option: CheckboxRecord) => (
            <Field name={option.name} type="checkbox" as={Cb} />
          ))}
        </React.Fragment>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-14
      • 2020-12-03
      • 2022-01-02
      • 2016-12-16
      • 2021-02-02
      • 2022-08-04
      • 2021-06-06
      • 1970-01-01
      相关资源
      最近更新 更多