常见的需求 实现在点击一个按钮时判断用户是否登陆 如果没登陆跳转登陆页面 登录了则正常执行函数处理

​tsx​

<Button onClick={sendMessage}>发送</Button>
const { verifyAuth } = useAuth();

const sendMessage = verifyAuth(() => {
console.log(text.current);
});

​useAuth​

interface IContext {
verifyAuth: <T extends (...args: any) => any>(callback: T) => () => T;
}

/**
* 验证是否有用户登陆 没有则打开登陆页面
*/
const verifyAuth: IContext["verifyAuth"] = callback => {
if (!auth._id) {
return userProfileRef.current!.open;
}
return callback;
};

​userProfileRef.current!.open();​

export const userProfileRef = createRef<{ open: () => void }>();

const UserProfile: FC<IProps> = (): ReactElement => {
const mask = useRef<HTMLDivElement>(null);

const open = useCallback(() => {
setShow(true);
}, []);

useImperativeHandle(userProfileRef, () => ({ open }), [open]);

return (
<Mask ref={mask} show={show}>
// 登陆组件内容
</Mask>
);
};

const Mask = styled.div<{ show: boolean }>`
display: ${props => (props.show ? 'flex' : 'none')};
`;