reactjs - react typescript : FunctionComponent with templated props

标签 reactjs typescript generics typescript-generics

我有一个带有模板化 Prop 的组件:

const MyComponent = <Value extends any>({ value }: MyComponentProps<Value>) => <div />;

我可以在不明确指定值类型的情况下使用它(这是推断的):

<MyComponent value="1" />
<MyComponent value={1} />

我通常这样编写组件:

const MyComponent: FunctionComponent<MyComponentProps> = ({ value }) => <div />;

但是还没有找到使用此语法模板 MyComponentMyComponentProps 的方法...有人知道该怎么做吗?提前致谢!

最佳答案

您可以像这样扩展 ComponentProps:

interface MyComponentProps<T> {
   value: T
}

const MyComponent: FunctionComponent<MyComponentProps<string>> = ({ value }) => <div />;

现在值是您在 <> 中传递的任何内容,例如字符串或任何值。

关于reactjs - react typescript : FunctionComponent with templated props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312503/

相关文章:

javascript - 如何跟踪选定的组件?

java - 获取一个类的所有类依赖项(包括泛型)?

c#通用接口(interface),其中参数是通用的

java - 如何创建读取制表符分隔文件的通用进程,并从中返回通用 Map

javascript - react : How to navigate through list by arrow keys

javascript - onFocus 干扰 onClick

typescript - 类型 'findAncestors' 上不存在属性 'Repository '

typescript - Cypress 在 Jest 断言中导致类型错误

javascript - 创建一个可以从 React 中任何地方访问的变量

javascript - 如何读取 Controller 中的表单值?