简体   繁体   English

如何编写 Typescript React 组件包装器

[英]How to write a Typescript React Component Wrapper

A custom ReactJS wrapper component should be used to wrap code and only render it, if the user has the required permission.如果用户具有所需的权限,则应使用自定义 ReactJS 包装器组件来包装代码并仅渲染它。 Therefore, it needs to accept two parameters, the children that shall be rendered as well as the permission it needs to check for.因此,它需要接受两个参数,即要渲染的孩子以及需要检查的权限。

The idea is to use it like this:我们的想法是像这样使用它:

const AdminTools = () => {
  return (
    <RequirePermission require_permission="ui:see_admin_menu">
      <>
        <h1>Sudo mode</h1>
        <Link href="/intern/users/">
          <a>
            <ActionCard link>User management</ActionCard>
          </a>
        </Link>
      </>
    </RequirePermission>
  );

};

What I came up with so far is the following code:到目前为止,我想出的是以下代码:

const RequirePermission = (children: React.FC<{}>, required_permission: string) => {
    const user = useContext(AuthContext);

    let hasPermission = false;
    if (user.state == AuthState.Authorized) {

        user.user?.realm_access?.roles.forEach(role => {
            if (permissions[role].includes(required_permission)) {
                hasPermission = true;
            }
        });
    }

    if (hasPermission) {
        return children;
    } else {
        return <div />;
    }

};

export default RequirePermission;

When using the code snippet as described above, the following error is thrown:使用上述代码片段时,会引发以下错误:

    Type '{ children: Element; require_permission: string; }' is not assignable to type 'IntrinsicAttributes & FC<{}>'.
  Property 'children' does not exist on type 'IntrinsicAttributes & FC<{}>'.ts(2322)
'RequirePermission' cannot be used as a JSX component.
  Its return type 'FC<{}> | Element' is not a valid JSX element.
    Type 'FunctionComponent<{}>' is missing the following properties from type 'Element': type, props, keyts(2786)

I don't really understand the error message to be frank.坦率地说,我真的不明白错误信息。 Any help would be much appreciated.任何帮助将非常感激。

//Edit: //编辑:

Error messages given by proposed code:建议代码给出的错误消息:

This JSX tag's 'children' prop expects a single child of type 'ReactChildren', but multiple children were provided.ts(2746)

and

'RequirePermission' cannot be used as a JSX component.
  Its return type 'Element | ReactChildren' is not a valid JSX element.
    Type 'ReactChildren' is missing the following properties from type 'Element': type, props, key

Try this, importing ReactChildren from react.试试这个,从 react 导入 ReactChildren。

I wish i could explain this better, but i know typescript is expecting a JSX/TSX element, so we could use ReactElement for the return type.我希望我能更好地解释这一点,但我知道 typescript 需要一个 JSX/TSX 元素,所以我们可以使用ReactElement作为返回类型。

For a better explanation on the children type为了更好地解释儿童类型

https://stackoverflow.com/a/58123882/7174241 https://stackoverflow.com/a/58123882/7174241

import React, { ReactChildren, ReactElement, ReactNode } from "react";

interface RequireType {
  children: ReactChildren | ReactNode | ReactElement;
  required_permission: string;
}

const RequirePermission = ({ children, required_permission }: RequireType):ReactElement => {
  const user = useContext(AuthContext);

  let hasPermission = false;
  if (user.state == AuthState.Authorized) {
    user.user?.realm_access?.roles.forEach((role) => {
      if (permissions[role].includes(required_permission)) {
        hasPermission = true;
      }
    });
  }

 return <>{hasPermission ? children : null}</>

};

export default RequirePermission;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM