0

我有以下组件决定是否应根据用户权限呈现组件:

const Can = forwardRef(({ requiredPermissions, children }, ref): null | JSX.Element => {
    const {
        user: { role },
        userPermissions,
    } = useAuth();

    return userHasPermission(role, userPermissions, requiredPermissions) ? children : null;
});

export default Can;

我需要做的是将在使用组件时ref将在内部的子组件传递给子组件Can

我怎样才能做到这一点?

4

2 回答 2

4

是的你可以。但是你需要做两件额外的事情:

  1. 您必须确保只有一个孩子被传递给组件。您可以使用方法检查它React.Children.only
  2. 用于React.cloneElement传递ref给孩子。
const Can = forwardRef(({ requiredPermissions, children }, ref): null | JSX.Element => {
    const {
        user: { role },
        userPermissions,
    } = useAuth();

    return userHasPermission(role, userPermissions, requiredPermissions) 
        ? React.cloneElement(React.Children.only(children), {
            ref,
          }) 
        : null;
});

export default Can;
于 2021-03-30T20:39:55.650 回答
1

使用React.ChildrenReact.cloneElement将 ref 道具传递给Can.

像这样:

const Can = forwardRef(
  ({ requiredPermissions, children }, ref): null | JSX.Element => {
    const {
      user: { role },
      userPermissions,
    } = useAuth();

    const childrenWithProps = () =>
      React.Children.map(children, (child) => {
        if (React.isValidElement(child)) {
          return (
            <React.Fragment>
              {React.cloneElement(child, {
                ref,
              })}
            </React.Fragment>
          );
        }
        return child;
      }) as React.ReactElement;

    return userHasPermission(role, userPermissions, requiredPermissions)
      ? childrenWithProps()
      : null;
  }
);

export default Can;
于 2021-03-30T20:41:43.977 回答