简体   繁体   English

React - 如何使用打字稿定义道具

[英]React - How to define props with typescript

I have a demo here这里有一个演示

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.

相关问题 Typescript:如何在 React 中定义条件 typescript 属性来访问 object? - Typescript: How to define conditional typescript props to access object in React? 如何使用 typescript 在 React 功能组件中定义自定义道具? - How to define custom props in a react functional component with typescript? TypeScript:在 React 中的 props 中传递组件时如何定义类型? - TypeScript: How to define the type when pass component in props in React? 如何为 props 中传递的对象定义 TypeScript 接口? - How to define TypeScript interface for the passed object in props? 如何在反应 typescript 中传递道具 - how to pass props in react typescript 如何在 TypeScript 中定义接口以正确传递道具? - How to define interfaces in TypeScript to pass the props correctly? 如何为React props定义TypeScript类型,只有在将prop A传递给组件时,才会接受prop B? - How do I define a TypeScript type for React props where prop B is only accepted if prop A is passed to a component? 使用 TypeScript Enum 和 PropTypes 来定义 React 组件道具 - Use TypeScript Enum with PropTypes to define React Component props 反应 select - 如何定义组件道具类型 - react select - how to define component props type 如何使用Flow定义反应导航的道具 - How to define props for react-navigation with Flow
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM