简体   繁体   English

用于React组件的Typescript prop类型的语法?

[英]Syntax for Typescript prop types for React component?

What is the syntax for adding proptypes to a React component with Typescript? 使用Typescript将原型添加到React组件的语法是什么? The following isn't working: 以下内容不起作用:

import React from "react";

type Props = {
  text: string;
  number: number;
};

function TextInput<Props>({ text, number }) {
  return (
    <div style={{ border: "1px solid gold" }}>
      <p>TEXT: {text}</p>
      <p>NUMBER: {number}</p>
    </div>
  );
}

export default TextInput;

You need to define the type of the parameter (which happens to be a destructure of the parameter). 您需要定义参数的类型(恰好是参数的分解)。

import React from "react";

type Props = {
  text: string;
  number: number;
};

function TextInput({ text, number }: Props) {
  return (
    <div style={{ border: "1px solid gold" }}>
      <p>TEXT: {text}</p>
      <p>NUMBER: {number}</p>
    </div>
  );
}

export default TextInput;

What you were defining was a function with a generic type parameter Props which is something very different. 您正在定义的是带有通用类型参数Props的函数,这是非常不同的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM