javascript - 在 React 中使用泛型定义 props

标签 javascript reactjs typescript

我通过以下方式将 React 与 TypeScript 结合使用:

interface MyComponentProps {
    ...
    ...
}

const MyComponent:FunctionComponent<MyComponentProps> = props => {
    ...
    ...
    ...
}

现在我需要定义以下 Prop 类型:

interface MyComponent2Props<T> {
    prop1: T,
    ...
}

我尝试定义组件:

const MyComponent2<T>:FunctionComponent<MyComponent2Props<T>> = props => {
    ...
    ...
    ...
}

但这是不正确的语法。

定义此类组件的正确方法是什么?

最佳答案

你可以尝试这样的事情:

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

interface Props<T> {
  a: T;
}

const Component = <T extends {}>(props: Props<T>) => {
  return <div>{props.a}</div>;
};

function App() {
  return <Component a="testing" />;
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

您可以 view the example here .

请注意 extends{}tsx 文件中是必需的。请参阅:What is the syntax for Typescript arrow functions with generics?

关于javascript - 在 React 中使用泛型定义 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57795969/

相关文章:

javascript - 使用 Angular 获取所有选定的复选框及其关联属性

Javascript - 将参数传递给函数以在 getElementById() 中使用

javascript - webpack 中的 css 配置不检测类样式但检测元素样式

css - 如何将鼠标悬停在 Angular 自动完成选项上

javascript - Angular 发布表单数据(文本输入)到 Rest API

javascript - React 的 setState 方法带有 prevState 参数

javascript - 错误 : <svg> attribute height: Expected length, "NaN"

reactjs - 错误: Unknown dataProvider function: toJSON

reactjs - 您的测试套件必须至少包含一项测试

typescript - 在保持 CommonJS 格式的同时过渡到 TypeScript