如何将组件传递给助手?
How would one pass a component to a helper?
我想将一个组件传递给助手并让该助手return一个对象数组,每个对象都有一个组件节点...
// helpers.ts
import { LINKS } from '../constants';
// error on the next line: Cannot find name 'Component'. ts(2304)
const createLinks = (component: Component) => {
return LINKS.map((props) => {
return ({
content: <Component {...props} />,
id: props.id
});
});
};
// component.tsx
import { List, SpecialLink } from '../components';
import { createLinks } from '../helpers';
const LinkList = () => {
const links = createLinks(SpecialLink);
return <List items={links}>
}
你应该使用react
的ComponentType
类型,所以组件参数可以是class组件或函数组件。
type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
import React from 'react';
import { ComponentType } from 'react';
const LINKS: any[] = [];
const createLinks = (Component: ComponentType) => {
return LINKS.map((props) => {
return {
content: <Component {...props} />,
id: props.id,
};
});
};
我想将一个组件传递给助手并让该助手return一个对象数组,每个对象都有一个组件节点...
// helpers.ts
import { LINKS } from '../constants';
// error on the next line: Cannot find name 'Component'. ts(2304)
const createLinks = (component: Component) => {
return LINKS.map((props) => {
return ({
content: <Component {...props} />,
id: props.id
});
});
};
// component.tsx
import { List, SpecialLink } from '../components';
import { createLinks } from '../helpers';
const LinkList = () => {
const links = createLinks(SpecialLink);
return <List items={links}>
}
你应该使用react
的ComponentType
类型,所以组件参数可以是class组件或函数组件。
type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
import React from 'react';
import { ComponentType } from 'react';
const LINKS: any[] = [];
const createLinks = (Component: ComponentType) => {
return LINKS.map((props) => {
return {
content: <Component {...props} />,
id: props.id,
};
});
};