【问题标题】:React - How to define props with typescriptReact - 如何使用打字稿定义道具
【发布时间】:2019-11-24 22:15:40
【问题描述】:

我有一个演示 here

这是一个使用 typescript 在 React 中简单的待办事项应用程序。

我正在尝试在 typescript 中定义道具。

我在 Todo 组件中有一个用于传递道具的接口

如果我尝试访问 Todo 组件中的文本,我会收到一条错误消息

Property 'text' does not exist on type 'string'.

如何使用 typescript 正确定义道具

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您将todo 定义为字符串,但您将其用作包含text 属性作为字符串的对象。因此,你的 props 定义应该是这样的:

    interface IProps {
      index: number,
      todo: { text: string }
    }
    

    【讨论】:

    • 这会产生另一个错误Error: Objects are not valid as a React child (found: object with keys {text, isComplete}). If you meant to render a collection of children, use an array instead.
    【解决方案2】:

    您需要使用接口来定义您的道具。看看下面的例子:

    import * as React from 'react'    
    
    interface IProps {
       name: string
       isActive?: boolean
    }
    
    const MyAwesomeComponent: React.FC<IProps> = ({name, isActive})=> (
        <p>Hello {name}. Your status is {isActive ? 'active': 'inactive'}</p>
    )
    

    name 是必需的,但不是 isActive

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2019-01-02
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2020-12-26
      • 2021-11-18
      相关资源
      最近更新 更多