[英]React - How to define props with typescript
It a simple todo app in React using typescript.它是一个在 React 中使用打字稿的简单待办事项应用程序。
I'm trying to define the props in typescript.我正在尝试在打字稿中定义道具。
I have an interface in the Todo component for the props being passed in我在 Todo 组件中有一个接口,用于传入的道具
If I try to access text in the Todo component I get an error saying如果我尝试访问 Todo 组件中的文本,我会收到一条错误消息
Property 'text' does not exist on type 'string'.
How do I define the props correctly using typescript如何使用打字稿正确定义道具
You're defining todo
as a string, but you're using it as an object that contains a text
property as a string.您将
todo
定义为字符串,但将其用作包含text
属性作为字符串的对象。 Therefore, you props definition should be like this:因此,你的道具定义应该是这样的:
interface IProps {
index: number,
todo: { text: string }
}
You need to use interface to define your props.你需要使用接口来定义你的道具。 Take a look at the example below:
看看下面的例子:
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
is required but not isActive
name
是必需的,但不是isActive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.