useLinkClickHandler

useLinkClickHandler用于获取一个用于处理导航组件被点击的事件的事件处理函数,这通常用于在自定义Link组件的时候执行导航功能的。以下是useLinkClickHandler的函数签名,可以在使用的时候参考。

declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(
  to: To,
  options?: {
    target?: React.HTMLAttributeAnchorTarget;
    replace?: boolean;
    state?: any;
  }
): (event: React.MouseEvent<E, MouseEvent>) => void;

以下示例将结合useHrefuseLinkClickHandler两个Hook来定义一个自定义的Link组件。

const StyledLink = styled.a`
  color: red;
`;

const Link = React.forwardRef(({ onCLick, replace = false, state, target, to, ...rest }, ref) => {
  let href = useHref(to);
  let handleClick = useLinkClickHandler(to, {
    replace,
    state,
    target
  });
  let compositeClickHandle = event => {
    onClick?.(event);
    if (!event.defaultPrevented) {
      handleClick(event);
    }
  };

  return <StyledLink {...rest} href={href} ref={ref} target={target} onClick={compositeClickHandle} />;
});