我正在使用带有打字稿的React15。下面是我的代码:
const WrappedComponent = (WrappedComponent: React.ComponentType<any>) => (<WrappedComponent className="my-class" />);
WrappedComponent(<div />);
我定义了一个接受任何反应组件的WrappedComponent
方法。然后我调用该方法传递<div />
元素。但是我得到了以下错误:
Argument of type 'Element' is not assignable to parameter of type 'ComponentType<any>'.
Type 'Element' is not assignable to type 'StatelessComponent<any>'.
Type 'Element' provides no match for the signature '(props: any, context?: any): ReactElement<any> | null'.
它报告有关Element
和ComponentType
的类型错误。我想知道如何将元素转换为反应组件方法。JSX 元素不是 React 组件吗?
另一个问题是关于如何定义一个通用组件属性来替换包装组件中的<any>
?
JSX 元素不是组件。JSX 反编译为React.createElement
调用,而不是组件:
https://reactjs.org/docs/jsx-in-depth.html
在 React 中,组件必须是使用渲染方法扩展Component
的类,或者是返回 JSX 的函数。
如果要在组件中传入并呈现任意 JSX,则只需使用children
.或者,如果您需要更复杂的东西,请尝试渲染道具:
const Wrapper = ({ render }) => <div>{render()}</div>
<Wrapper render={() => <div/>} />