我有一个带有模板化道具的组件:
const MyComponent = <Value extends any>({ value }: MyComponentProps<Value>) => <div />;我可以在不显式指定值类型的情况下使用它(这是推断出来的):
<MyComponent value="1" />
<MyComponent value={1} />我通常这样写我的组件:
const MyComponent: FunctionComponent<MyComponentProps> = ({ value }) => <div />;但是还没有找到一种使用这种语法来模版MyComponent和MyComponentProps的方法...有人知道怎么做吗?提前感谢!
发布于 2019-08-01 23:56:47
您可以像这样扩展ComponentProps:
interface MyComponentProps<T> {
value: T
}
const MyComponent: FunctionComponent<MyComponentProps<string>> = ({ value }) => <div />;现在,值是您在<>中传递的任何内容,例如string或any。
发布于 2019-08-02 15:35:59
根据你的评论,你只需要这样:
interface MyComponentProps<V> {
views: V;
initialView: keyof V;
}
type KeyedFunctionComponent<T> = FunctionComponent<MyComponentProps<T>>;
const MyComponent: KeyedFunctionComponent<Views> = (views, initialViews) => <div />;然后使用接口或"typeof views“作为泛型参数来声明函数组件。我觉得这很好。但是,你真正想要的是它与一个生成器相结合,它将允许你正确地绑定和模板:
// 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发布于 2019-08-02 15:46:31
如果您希望value是任何类型:
type MyComponentProps = {
value: any
};或仅显式类型之一(也称为联合类型):
type MyComponentProps = {
value: string | number
};
const MyComponent: FunctionComponent<MyComponentProps> = ({ value }) => <div />;https://stackoverflow.com/questions/57312503
复制相似问题