[英]How to define TypeScript interface for the passed object in props?
[英]How to define this interface Props so that this Props contains all the attributes of the passed component
interface Props {
component: any;
}
function Example(props: Props) {
const {component: Component, children} = props
return <Component>{children}</Component>
}
例如:在react-native中传入的组件是TouchableOpacity,那么Example组件会自动继承TouchableOpacity的所有Props。 你可以这样写,Typescript 不会报错:
<Example component={TouchableOpacity} onPress={handleSomePress} />
我是 TypeScript 的新手,这个问题困扰了我很长时间。 期待一个完美的答案,祈祷。
您将必须使用泛型并获取 Typescript 以根据您分配的组件推断属性。
// Prop type for wrapper component
type WrapperProps<TComponent extends React.ComponentType<any> = any> =
// component prop will be used to both pass the component to render
// and to get the Typing for the component, once the component is assigned
// Typescript will infer TComponent and propagate it thoughout the rest of
// the type.
{ component: TComponent; } &
// Add all the props from the passed in component.
React.ComponentProps<TComponent>;
// Create the component.
// The component must pass the generics as well otherwise they will be defaulted
// to any and no infered typing will occur.
const Wrapper = <TComponent extends React.ComponentType<any> = any>({
// Get component from props.
component,
// Get the rest of the passed in props
...restProps
}: WrapperProps<TComponent>) => {
// To render a custom component the variable must start with a capital.
const Component = component;
// Here you could modify or remove props that have been passed in,
// or apply defaults to missing props etc.
// Render component with props.
return <Component {...restProps} />;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.