我通过以下方式将 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/