![](/img/trans.png)
[英]Typescript: How to define conditional typescript props to access object in React?
[英]React - How to define props with typescript
我這里有一個演示
它是一個在 React 中使用打字稿的簡單待辦事項應用程序。
我正在嘗試在打字稿中定義道具。
我在 Todo 組件中有一個接口,用於傳入的道具
如果我嘗試訪問 Todo 組件中的文本,我會收到一條錯誤消息
Property 'text' does not exist on type 'string'.
如何使用打字稿正確定義道具
您將todo
定義為字符串,但將其用作包含text
屬性作為字符串的對象。 因此,你的道具定義應該是這樣的:
interface IProps {
index: number,
todo: { text: string }
}
你需要使用接口來定義你的道具。 看看下面的例子:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.