【发布时间】:2020-12-05 06:05:55
【问题描述】:
我想创建一个组件来处理具有相同属性/逻辑的多个 HTML 元素。
import React from 'react';
import styled from 'styled-components';
interface GridProps {
htmlElement: 'div' | 'main' | 'header',
}
const GridFactory = (props: GridProps) => {
switch (props.htmlElement) {
case 'header':
return styled.header``;
case 'main':
return styled.main``;
case 'div': default :
return styled.div``;
}
}
export const Test = () => (
<GridFactory htmlElement='div'>
<p>content...</p>
</GridFactory>
)
它因该错误而失败:
Type '{ children: Element; htmlElement: "div"; }' is not assignable to type 'IntrinsicAttributes & GridProps'.
Property 'children' does not exist on type 'IntrinsicAttributes & GridProps'.
尝试了第一个技巧
向 GridProps 添加显式的 children 道具:
interface GridProps {
htmlElement: 'div' | 'main' | 'header',
children?: React.ReactNode | React.ReactNode[];
}
它给出了相应的错误:
'GridFactory' cannot be used as a JSX component.
Its return type 'StyledComponent<"header", DefaultTheme, {}, never> | StyledComponent<"div", DefaultTheme, {}, never>' is not a valid JSX element.
Type 'StyledComponent<"header", DefaultTheme, {}, never>' is not assignable to type 'Element | null'.
Type 'String & StyledComponentBase<"header", DefaultTheme, {}, never> & NonReactStatics<never, {}>' is missing the following properties from type 'Element': type, props, key
我怎样才能实现它?
【问题讨论】:
标签: javascript reactjs typescript styled-components