React Redux 是一个连接 Redux store 和 react 组件的库, React Redux 大量使用高阶组件模式。
Higher order component (HOC) : A component (HOC) that renders another component (regular component).
高阶组件 HOC 呈现另一个常规组件。
通过使用高阶组件模式,可以修改一系列存在的组件,避免多次重写代码。
代码举例:
import React from "react";
import ReactDOM from "react-dom";
const Info = (props) => (
<div>
<h1>Info</h1>
<p>The info is: {props.info}</p>
</div>
);
const requireAuthentication = (WrappedComponent) => {
return (props) => (
<div>
{props.isAuthenticated ? (
<WrappedComponent {...props} />
) : (
<p>Please login to view the info.</p>
)}
</div>
);
};
const AuthInfo = requireAuthentication(Info);
ReactDOM.render(
<AuthInfo isAuthenticated={true} info="There are the details" />,
document.getElementById("app")
);
高阶组件的目标是实现代码重用,同一高阶组件可以呈现多个组件。
以上代码,requireAuthentication
是常规函数,返回高阶组件。
如果 isAuthenticated
为true
,呈现传递进去的 WrappedComponent
,否则,显示 Please login to view the info
,不管传递什么组件作为参数,都是一样的效果。