首页 > 解决方案 > 在没有 forwardRef 的情况下处理函数组件中的 ref

问题描述

我遇到了裁判的情况,只是在寻找解决方法。

https://github.com/styleguidist/react-docgen-typescript/issues/314

使用本质上是 React.forwardRef 的实用程序方法破坏了我的 Storybook 中的自动类型文档。

我不介意暂时导出 2 个组件:

  1. 一个没有 forwardRef 的 Storybook
  2. 一个带有 forwardRefWithAs 的应用程序使用

然而,这显然不只是......“工作”,因为 refs 没有在正常函数中隐式传递。

这样的事情可行吗?有什么问题吗?

// i'll use a generic
const useForwardedRef = (ref: React.Ref<any>) =>{
  const innerRef = useRef<any>(null);
  useEffect(() => {
    if (!ref) return;
    if (typeof ref === 'function') {
      ref(innerRef.current);
    } else {
      ref.current = innerRef.current;
    }
  });
 
  return innerRef;
}

我也可以这样做:

export const ButtonWithoutForwardRefWithAs = forwardRef((props: ButtonProps, ref: React.Ref<any>) => <JSX {...props} ref={ref} />

const Button = forwardRefWithAs<NonSemanticButtonProps, 'button'>((props: ButtonProps, ref) => (
  <ButtonWithoutForwardRefWithAs {...props} ref={ref} />
));

你怎么看?

标签: reactjstypescriptstorybookreact-forwardref

解决方案


这最终与实用程序方法无关。相反,它与我如何导出东西有关。

之前:

const Button = forwardRefWithAs<NonSemanticButtonProps, 'button'>((props: ButtonProps, ref) => (
  <ButtonWithoutForwardRefWithAs {...props} ref={ref} />
));

Button.displayName = 'Button';

export { Button };

在职的:

export const Button = forwardRefWithAs<NonSemanticButtonProps, 'button'>((props: ButtonProps, ref) => (
  <ButtonWithoutForwardRefWithAs {...props} ref={ref} />
));

Button.displayName = 'Button';

推荐阅读