理解 React 高阶组件

Understanding React Higher-Order Components

有人可以解释一下 React 中的高阶组件吗?我已经阅读并重新阅读了文档,但似乎无法更好地理解。根据文档,HOC 通过创建一个 returns 反应组件的主要函数,通过将参数传递给该函数来帮助消除重复。 我有几个问题。

运行 这不显示 HOC,仅显示 div

谁能提供比给出的例子更好的例子?

试试你的createSetup.js:

const createSetup = options => <p>{options.name}</p>;

和你的main.js

const comp = createSetup({ name: 'name' });
render((<div>{comp}</div>),
  document.getElementById('root'));

HOC 是一个函数,它将组件作为其参数之一并以某种方式增强该组件。

If HOCs create a new enhanced component, can it be possible not to pass in any component as argument at all?

不,那么它就不是 HOC,因为其中一个条件是它们将一个组件作为参数之一,并且它们 return 一个具有一些附加功能的新组件。

In an example such as this, which is the higher order component, the Button or the EnhancedButton.

EnhanceButton 是 HOC,FinalButton 是增强组件。

I tried creating one HOC like this: ... Running this does not show the HOC, only the div

那是因为你的 createSetup 函数不是 HOC...它是一个 return 是一个组件的函数,是的,但它没有将组件作为参数来增强它.

让我们看一个基本 HOC 的例子:

const renderWhen = (condition, Component) =>
  props => condition(props)
    ? <Component {...props} />
    : null
);

你可以这样使用它:

const EnhancedLink = renderWhen(({invisible}) => !invisible, 'a');

现在您的 EnhancedLink 将像一个 a 组件,但如果您将 属性 invisible 设置为 true,它将不会呈现。 .. 所以我们增强了 a 组件的默认行为,您可以对任何其他组件执行此操作。

在许多情况下,HOC 函数是柯里化的,组件参数放在最后...像这样:

const renderWhen = condition => Component =>
  props => condition(props)
    ? <Component {...props} />
    : null
);

喜欢react-redux的connect功能...这使得组合更容易。看看 recompose.

简而言之,如果您假设函数类似于组件,则闭包类似于 HOC。

高阶组件 (HOC) 是 React 中用于重用组件逻辑的高级技术。具体来说,高阶组件是一个接受组件和 returns 新组件的函数。

A HOC is a pure function with zero side-effects.

示例:有条件地渲染组件

假设我们有一个仅在用户通过身份验证时才需要呈现的组件——它是一个受保护的组件。我们可以创建一个名为 WithAuth() 的 HOC 来包装受保护的组件,然后在 HOC 中进行检查,如果用户已通过身份验证,该 HOC 将仅呈现该特定组件。

一个基本的withAuth() HOC,根据上面的例子,可以写成如下:

// withAuth.js
import React from "react";
export function withAuth(Component) {
    return class AuthenticatedComponent extends React.Component {
        isAuthenticated() {
            return this.props.isAuthenticated;
        }

        /**
         * Render
         */
        render() {
            const loginErrorMessage = (
                <div>
                    Please <a href="/login">login</a> in order to view this part of the application.
                </div>
            );

            return (
                <div>
                    { this.isAuthenticated === true ? <Component {...this.props} /> : loginErrorMessage }
                </div>
            );
        }
    };
}

export default withAuth;

上面的代码是一个名为 withAuth 的 HOC。它基本上需要一个组件和 returns 一个名为 AuthenticatedComponent 的新组件,用于检查用户是否已通过身份验证。如果用户未通过身份验证,则 returns loginErrorMessage 组件;如果用户通过身份验证,它 returns 包装组件。

Note: this.props.isAuthenticated has to be set from your application’s logic. (Or else use react-redux to retrieve it from the global state.)

要在受保护的组件中使用我们的 HOC,我们会像这样使用它:

// MyProtectedComponent.js
import React from "react";
import {withAuth} from "./withAuth.js";

export class MyProectedComponent extends React.Component {
    /**
     * Render
     */
    render() {
        return (
            <div>
                This is only viewable  by authenticated users.
            </div>
        );
    }
}

// Now wrap MyPrivateComponent with the requireAuthentication function 
export default withAuth(MyPrivateComponent);

在这里,我们创建了一个只有经过身份验证的用户才能查看的组件。我们将该组件包装在我们的 withAuth HOC 中,以保护该组件免受未经身份验证的用户的影响。

Source