让 React 高阶组件 HOC 变得简单
在开始学习高阶组件之前,我们需要先明确高阶函数的概念。
JavaScript 中的高阶函数
高阶函数是一种函数 -
- 以函数作为参数
- 返回另一个函数
好的,让我们看一个 JavaScript 中高阶函数的例子。
function sum(a, b) {
return a + b;
}
function multiplication(a, b) {
return a * b;
}
// result() is a Higher Order Function
function result(operation) { // operation is actually an another function
return function(a, b) { // return function
return "Result of operation: " + operation(a, b);
}
}
const sumResult = result(sum);
const multipleicationResult = result(multiplication);
console.log(sumResult(1, 200)); // Result of operation: 201
console.log(multipleicationResult(2, 200)); // Result of operation: 400
在上面的例子中,result()
是一个高阶函数,它接受算术运算作为参数。
然后,它返回一个函数,并以某种方式操作它并返回函数数据。
所以,通过这种方法 - 我们不必重复
运行结果:
文本。我们可以重复使用整个sum()
,multiplication()
函数。
现在,我们来谈谈高阶组件-
高阶组件是一个纯 JavaScript 函数,它 -
- 以组件作为参数
- 返回另一个组件
例如:
假设我们有 2 个页面,分别称为“关于页面”和“主页”,组件可能如下所示:
HomePage
成分
import React from "react";
const HomePage = () => {
return (
<div>
<header>
Some Header Content
</header>
<div title="Home Page">
<h2>Home Page</h2>
</div>
<footer>
Some Footer Content
</footer>
</div>
);
};
export default HomePage;
AboutPage
成分
import React from "react";
const AboutPage = () => {
return (
<div>
<header>
Some Header Content
</header>
<div title="About Page">
<h2>About Page</h2>
</div>
<footer>
Some Footer Content
</footer>
</div>
);
};
export default AboutPage;
但是,看这里,我们为这两个组件复制了相同的 Header 和 Footer 部分。所以现在,我们可以轻松地使用高阶组件来复用这个逻辑。
hocs/Layout.js
import React from "react";
const withLayout = (PageComponent) => {
return function WithPage({ ...props }) {
return (
<div>
<header>
Some Header Content
</header>
<!-- Called The Component Parameter -->
<PageComponent />
<footer>
Some Footer Content
</footer>
</div>
);
};
};
export default withLayout;
太棒了,现在我们可以非常轻松地使用我们的 HomePage 和 AboutPage 组件。
import React from "react";
import withLayout from "./hocs/Layout";
const HomePage = () => {
return (
<div title="Home Page">
<h2>HomePage</h2>
</div>
);
};
export default withLayout(HomePage);
import React from "react";
import withLayout from "./hocs/Layout";
const AboutPage = () => {
return (
<div title="About Page">
<h2>About Page</h2>
</div>
);
};
export default withLayout(AboutPage);
因此,我们可以withLayout
在任何我们想要的页面上使用这个 hoc。
通过大量用例和高阶组件示例来全面学习 - https://devsenv.com/tutorials/higher-order-component-in-react-in-depth-discussion-about-react-hoc
在 Github 上关注我 - https://github.com/ManiruzzamanAkash
文章来源:https://dev.to/maniruzzamanakash/make-react-higher-order-component-hoc-an-easy-one-2noa