首页 > 解决方案 > 为什么我不能将一般 JSX 传递给反应中的包装组件?

问题描述

我正在使用带有打字稿的 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。我想知道如何将 Element 转换为 react 组件方法。JSX 元素不是 React 组件吗?

另一个问题是关于如何<any>在 WrappedComponent 中定义要替换的通用组件属性?

标签: reactjstypescript

解决方案


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/>} />

推荐阅读