React:在高阶组件中包含子组件的新道具

React: Include new prop to the Child Component in Higher Order Component

这是高阶组件class

token 是我要包含的 prop

   import React from "react";
    
    export function requireAuthentication(Component) {
        return class AuthenticatedComponent extends React.Component {
    

            isAuthenticated() {
                return this.props.isAuthenticated;
            }

            render() {;
    
                return (
                    <div>
                        { this.isAuthenticated === true ? <Component token={token} {...this.props} /> }
                    </div>
                );
            }
        };
    }
    
    export default requireAuthentication;

当我访问 Componentprops 时,我得到 props.token 作为 undefined?有没有办法传递新道具?

我想如果组件有另一个名为 isAuthenticated 的道具,您需要将 token 传给组件。你可以像下面那样做。

import React from "react";

export function requireAuthentication(Component) {
  return class AuthenticatedComponent extends React.Component {
    isAuthenticated() {
      return this.props.isAuthenticated;
    }

    render() {
      return (
        <div>
          {this.props.isAuthenticated === true ? (
            <Component
              token={"this_token_is_retrieved_by_requireAuthentication"}
              {...this.props}
            />
          ) : (
            <Component {...this.props} />
          )}
        </div>
      );
    }
  };
}

const MyComp = requireAuthentication(({ token }) => {
  return <div>token: {token}</div>;
});

export default function App() {
  return (
    <div className="App">
      <MyComp isAuthenticated={true} />
      <MyComp isAuthenticated={false} />
    </div>
  );
}

Code sandbox