【问题标题】:Typescript & React: Passing props between components vs default propsTypescript & React:在组件之间传递道具与默认道具
【发布时间】:2020-01-25 08:48:40
【问题描述】:

我对 Typescript 还很陌生,并使用 Typescript 创建了一个 React 应用程序。我在将道具从一个组件传递到另一个组件时遇到了一些麻烦。我在下面提供了一个示例,我的问题是关于组件的默认道具。

当我在父组件中调用子组件时,出现错误:

Type '{}' is missing the following properties from type 'IProps': className, disabled ts(2739)

我认为因为我的子组件上有默认的 props,所以当从其他组件调用该组件时,它们会填补任何缺失的 props。

我知道我可以使用className?: string 在我的子组件中的接口IProps 中将单个道具设为可选,但这不是我正在寻找的解决方案,因为它带来的问题多于解决的问题。

当我从另一个组件(如下所示)调用子组件时,我宁愿不必注意每个默认道具,因为对于某些组件,我有很多道具: <Child class={''} disabled={false} />

我确信有一个相当简单的解决方案,但到目前为止我找不到任何方向。欢迎任何建议或指导。

// Parent component: 

import React, { FC } from 'react'

import Child from './child'

const Parent: FC = () => {
    return (
        <Child />
    )
}

export default Parent


// Child component: 

import React, { FC } from 'react'

interface IProps {
  className: string
  disabled: boolean
}

const Child: FC<IProps> = ({ className, disabled }: IProps) => {
  return (
    <button className={className} disabled={disabled}>
      Click here
    </button>
  )
}

Child.defaultProps = {
  className: '',
  disabled: false,
}

export default Child

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您做得对,但错过了传递 className 和禁用子组件的 props。

    const 父级:FC = () => { 返回 ( ) }

    【讨论】:

    • Stackoverflow 不是聊天工具
    【解决方案2】:

    解决了这个问题,任何人都在看这个答案:只需要按照下面的代码将默认道具以及任何道具传递到组件中:

    import React, { FC } from 'react'
    
    interface IProps {
      className: string
      disabled: boolean
    }
    
    const Child: FC<IProps & Child.defaultProps> = ({ className, disabled }: IProps) => {
      return (
        <button className={className} disabled={disabled}>
          Click here
        </button>
      )
    }
    
    Child.defaultProps = {
      className: '',
      disabled: false,
    }
    

    【讨论】:

      【解决方案3】:

      您可以提供默认参数来阻止这种情况发生:

      const Child: FC<IProps> = ({ className = 'foo', disabled = false }: IProps) => {
        ...
      }
      

      这实际上应该解决您遇到的可选道具问题,特别是如果您使用这些默认参数(即,懒惰的开发人员不检查哪些道具是必需的/可选的)。现在您可以将它们设为可选...

      【讨论】:

      • 谢谢,我已经尝试过了,不幸的是没有用。我认为问题是当组件在父组件中实例化时,它看到道具是必需的,并且不会检查参数中的默认道具或Child.defaultProps
      • 如果你修改界面以使两个道具都是可选的,这会发生@paulosullivan22 吗?
      • 在界面中使道具可选确实可以解决错误,但我希望避免这种情况,因为在组件主体中使用道具时会出现很多问题
      • 也许这有帮助:medium.com/@martin_hotell/…
      猜你喜欢
      • 2019-12-27
      • 2020-05-01
      • 2018-12-17
      • 2021-04-01
      • 2018-05-26
      • 2018-08-22
      • 2021-07-21
      • 2020-10-19
      • 2017-09-04
      相关资源
      最近更新 更多