【发布时间】:2019-08-21 07:15:52
【问题描述】:
我正在尝试在 React 中实现一些不断出现错误的类型。
我的想法是我有一个枚举(EBreakpoint),它与我们支持的每个设备键控。代理包装器组件将每个设备作为一个道具,并将值作为道具解析给子组件。
TypeScript 部分有效,as I've demonstrated in a Typescript Playground,但实现不断收到此错误:
JSX element type 'Element[] | IChild<any>' is not a constructor function for JSX elements.
Type 'Element[]' is missing the following properties from type 'Element': type, props, key
Codesandbox URL:https://codesandbox.io/s/serene-sea-3wmxk(去掉部分代理功能,尽可能隔离问题)
index.tsx:
import * as React from "react";
import { render } from "react-dom";
import { Proxy } from "./Proxy";
import "./styles.css";
const ChildElement: React.FC<{ text: string }> = ({ text }) => {
return <>{text}</>;
};
function App() {
return (
<div className="App">
<Proxy Mobile={{ text: "Mobile" }}>
<ChildElement text="Default" />
</Proxy>
</div>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
Proxy.tsx:
import * as React from "react";
enum EBreakpoint {
Mobile = "Mobile",
Desktop = "Desktop"
}
interface IChild<P> extends React.ReactElement {
props: P;
}
type TResponsiveProps<P> = { [key in EBreakpoint]?: P };
interface IProps<P> extends TResponsiveProps<P> {
children: IChild<P>;
}
export function Proxy<P>({ children, ...breakpoints }: IProps<P>) {
return Object.keys(breakpoints).length && React.isValidElement(children)
? Object.keys(breakpoints).map(breakpoint => (
<div>{React.cloneElement(children, breakpoints[breakpoint])}</div>
))
: children;
}
【问题讨论】:
-
这是 JSX 中的某种错误,尽管接口没有被完全解析?
标签: reactjs typescript