首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Typescript:带有模板道具的FunctionComponent

问React Typescript:带有模板道具的FunctionComponent
EN

Stack Overflow用户
提问于 2019-08-01 23:34:57
回答 4查看 604关注 0票数 2

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

代码语言:javascript
复制
const MyComponent = <Value extends any>({ value }: MyComponentProps<Value>) => <div />;

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

代码语言:javascript
复制
<MyComponent value="1" />
<MyComponent value={1} />

我通常这样写我的组件:

代码语言:javascript
复制
const MyComponent: FunctionComponent<MyComponentProps> = ({ value }) => <div />;

但是还没有找到一种使用这种语法来模版MyComponent和MyComponentProps的方法...有人知道怎么做吗?提前感谢!

EN

回答 4

Stack Overflow用户

发布于 2019-08-01 23:56:47

您可以像这样扩展ComponentProps:

代码语言:javascript
复制
interface MyComponentProps<T> {
   value: T
}

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

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

票数 1
EN

Stack Overflow用户

发布于 2019-08-02 15:35:59

根据你的评论,你只需要这样:

代码语言:javascript
复制
interface MyComponentProps<V> {
    views: V;
    initialView: keyof V;
}

type KeyedFunctionComponent<T> = FunctionComponent<MyComponentProps<T>>;

const MyComponent: KeyedFunctionComponent<Views> = (views, initialViews) => <div />;

然后使用接口或"typeof views“作为泛型参数来声明函数组件。我觉得这很好。但是,你真正想要的是它与一个生成器相结合,它将允许你正确地绑定和模板:

代码语言:javascript
复制
// Declare some views constant:
const views = { home: "home", index: "index" };


// Declare a type for our bound views component
interface KeyedProps<V> {
    initialView?: keyof V;
}


// declare a type for our input function
interface KeyedWithViewsProps<V> extends KeyedProps<V> {
    views: V;
}


// This is the binding function itself
function createKeyedComponent<T>(views: T, toWrap: FunctionComponent<KeyedWithViewsProps<T>>): FunctionComponent<KeyedProps<T>> {
    return (props: KeyedProps<T>) => toWrap({views, initialView: props.initialView});
}


// Call the binder, and pass in the function we want to bind.
const MyComponent = createKeyedCompnonet(views, () => <div />);

// Now, using the component, only requires the optional initialView param, and it it type-checked to ensure it is a member of views
<MyComponent initialView="home" /> // works
<MyComponent initialView="other" /> // doesn't work
票数 1
EN

Stack Overflow用户

发布于 2019-08-02 15:46:31

如果您希望value是任何类型:

代码语言:javascript
复制
type MyComponentProps = {
  value: any
};

或仅显式类型之一(也称为联合类型):

代码语言:javascript
复制
type MyComponentProps = {
  value: string | number
};

const MyComponent: FunctionComponent<MyComponentProps> = ({ value }) => <div />;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57312503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档