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



这是高阶组件类

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>
  );
}

代码沙盒

最新更新