在reactjs中声明后将道具传递给组件

问题描述

我正在尝试实现本教程中所见的基于角色的身份验证 REACT AUTHENTICATION TUTORIAL

这是我的 react-router-dom 函数

<Switch>
  <Route exact path="/addcloth" component={Authorization(AddCloth,[1],role,[storelist,sectionlist])} />
<Switch />

这是我的授权功能

    export default function Authorization(WrappedComponent,allowedRoles,userType,property) {
        return class WithAuthorization extends React.Component {
            render() {
                if (allowedRoles.includes(userType)) {
                    let Component = <WrappedComponent />;
                    // some code to add property elements into Component
                    return Component;
                } else {
                    return (
                        <AccessDenied />
                    );
                }
            }
        };
    };

因为 storelist 和 sectionlist 是 AddCloth 组件的 2 个道具,我正在尝试将其传递到 AddCloth。在教程中他没有提到相同的内容

解决方法

你快到了。您需要将其作为对象发送。

<Switch>
  <Route exact path="/addcloth" component={Authorization(AddCloth,[1],role,{storelist,sectionlist})} />
<Switch />

在 HOC 中,解构 props 并分配给组件。

    export default function Authorization(WrappedComponent,allowedRoles,userType,props) {
    return class WithAuthorization extends React.Component {
        render() {
            if (allowedRoles.includes(userType)) {
                let Component = <WrappedComponent {...props} />;
                // some code to add property elements into Component
                return Component;
            } else {
                return (
                    <AccessDenied />
                );
            }
        }
    };
};