首页 > 解决方案 > 导航中如何根据 HOC 函数让 react 组件读取或编辑?

问题描述

我想根据授权使组件读取或编辑。例子

const auth = "read" || "edit"

如果 auth 是 read 用户只能允许读取组件。如果 auth 是 edit,用户可以允许编辑组件。

如何将所有组件包装到全局 HOC 函数并基于身份验证如何导航。

导航容器


<Stack.Navigator initialRouteName="LoginComponent">
      <Stack.Screen
        name="LoginScreen"
        component={LoginComponent}
        options={{
          headerShown: false,
          gestureEnabled: false,
        }}
      />
 <Stack.Screen
        name="Upload"
        component={Uploadcompoenent}
        options={{
          headerShown: false,
          gestureEnabled: false,
        }}
      />
</Stack.Navigator>

(健康)状况

1.让考虑如果用户主管然后用户可以上传新图像。2.如果用户是助理主管,用户只能阅读屏幕。对于助理主管上传选项被禁用。

我想将所有组件放入一个基于 auth 用户可以读取或上传图像的 HOC 函数中。

谢谢,

任何线索将不胜感激:)

标签: reactjsreact-nativeuinavigationcontroller

解决方案


将组件 <Stack.Navigator/> 视为 HOC,它将呈现几个子元素。

在 Stack.Navigator 组件中,您将拥有可以使用 React.Children.map 以这种方式传递给所有子组件的 auth 值:

export default function ParentComp(props) {
  const auth = 'edit';

  return React.Children.map(props.children, (child, i) => {
    let el = React.cloneElement(child, {
      auth
    });
    return el;
  });
}

因此,您的子组件将接受您的身份验证状态作为道具,用于阻止子组件上的某些事件。

export default function ChildComp(props) {
  return (
    <div>
      component is only {props.auth} {props.test}
    </div>
  );
}

推荐阅读