reactjs - 为什么我不能将一般 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 中定义要替换的通用组件属性?
解决方案
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/>} />
推荐阅读
- google-sheets - 获取'String不是'List类型的子类型
' 调用 clientViaServiceAccount 时出错 - javascript - Google Maps Javascript 地图中心更新
- firebase - Firebase 电子邮件验证无效证书问题
- eclipse - 无法在 Eclipse 中添加 SVN 存储库 WSIG
- c++ - 带节点的链表
- android - 如何通过指纹以 xamarin 形式注册用户?
- mysql - 当我使用select语句时,我的sql多次输出相同的数据
- javascript - 如何检查某个值是否已存在于 Firebase 集合中?
- hibernate - 多数据源配置和使用 hikari 在 sping boot 2 中的使用
- android - 支持自定义视图的 RTL