当然!Standard Component 是一个可重用的部件,甚至 HOC 也是一个组件,用于重用组件逻辑。
高阶组件只是一个封装了另一个组件的 React 组件。
React HOC 模式通常被实现为一个函数,它基本上是一个类工厂,在 haskell 启发的伪代码中具有以下签名
hocFactory:: W: React.Component => E: React.Component
W (WrappedComponent) 是被包装的 React.Component
E(增强组件)是新的、HOC、React.Component
返回。
定义的“包装”部分故意含糊其辞,因为它
可以表示以下两种情况之一:
- 道具代理:HOC 操纵传递给的道具
WrappedComponent W。
- 继承反转:HOC 扩展了 WrappedComponent W。
在高级别的 HOC 中,您可以:
- 道具操作
- 代码重用、逻辑和引导抽象
- 状态抽象和操作
- 渲染劫持
使用标准组件时无法更改。
所以基本上如果你需要操纵道具并干扰渲染过程,你必须使用 HOC 而不是标准组件。
HOC 的简单示例
import React from 'react';
import AuthService from '../services/AuthService';
const AuthContext = React.createContext();
export default class AuthProvider extends React.Component {
constructor(props) {
super(props);
this.state = {
authService: new AuthService(),
loggedIn: false,
userSigninFetching: true,
userSigninError: '',
user: null
}
}
componentWillMount() {
this.processAuthState();
}
processAuthState = () => {
this.setState({ userSigninFetching: true });
const user = JSON.parse(localStorage.getItem('user'))
if (!user) {
this.setState({
loggedIn: false,
userSigninFetching: false,
userSigninError: "Login Failed",
user: null
});
return;
}
this.setState({
loggedIn: true,
userSigninFetching: false,
userSigninError: "Successfully Logged In",
user: user
});
}
render() {
return (
<AuthContext.Provider value={{ authState: this.state }}>
{this.props.children}
</AuthContext.Provider>
)
}
}
export const withAuth = (BaseComponent) => class AuthComponent extends React.Component {
render() {
return (
<AuthContext.Consumer>
{(context) => (
<BaseComponent
{...this.props}
authState={context ? context.authState : {
loggedIn: false,
userSigninFetching: false,
userSigninError: "",
user: null
}}
/>
)}
</AuthContext.Consumer>
)
}
}
现在让我们用 withAuth 包装您的组件,以便从组件本身访问身份验证状态。
import { withAuth } from '../providers/AuthProvider';
const myComponent = ({ authState }) => {
return (
<div>Custom component</div>
);
}
export default withAuth(myComponent);
所以现在您可以在 myComponent 中访问您的应用程序身份验证状态。
块引用
Here is the react guide for HOC
Also a good blog to dive in to depth of HOC