包装函数需要两个输入,一个是组件,另一个是类名。 我的问题是,为什么我们返回后不直接使用jsx代码呢? 为什么我们在return后面放一个箭头函数呢? 如果我返回后直接使用jsx代码,会出现以下错误
import React from "react";
const Wrapper = (WrappedComponent, className) => {
return (props) => (
<div className={className}>
<WrappedComponent />
</div>
);
};
export default Wrapper;
更高阶组件,
Wrapper
(在您的情况下)将按如下方式使用:
const WrappedComponent = Wrapper(SomeComponent, 'someClassName');
const App = () => {
// some code here you know
return (
<div>
....
<WrapperComponent />
</div>
);
}
那么看看
WrapperComponent
是如何渲染的?它被渲染为普通的反应组件,即这个语法<WrapperComponent />
。因此,与任何其他 React 组件一样,WrappedComponent
可以是类组件,也可以是函数组件(由 Wrapped
返回)。
如果
Wrapped
按照你所说的直接返回jsx,你将无法渲染作为react组件返回的内容!