reactjs - 在没有 forwardRef 的情况下处理函数组件中的 ref
问题描述
我遇到了裁判的情况,只是在寻找解决方法。
https://github.com/styleguidist/react-docgen-typescript/issues/314
使用本质上是 React.forwardRef 的实用程序方法破坏了我的 Storybook 中的自动类型文档。
我不介意暂时导出 2 个组件:
- 一个没有 forwardRef 的 Storybook
- 一个带有 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} />
));
你怎么看?
解决方案
这最终与实用程序方法无关。相反,它与我如何导出东西有关。
之前:
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';
推荐阅读
- javascript - IONIC 3 - 以编程方式清除应用程序数据
- vue.js - Vue 路由器,router.onReady()
- php - 使用 php 包含重用代码时出现意外的“<”
- python - Python使用基于IF条件的ElementTree解析XML
- git - GIT / bitbucket - 如何在bitbucket的主服务器上排除1次提交后被推送
- css - 如何更改引导边框的颜色(不是表格边框)
- azure - 是否可以在 azure VM 中运行 Docker CE?
- android - Android、Firestore、跨活动的用户数据共享
- google-speech-api - Google Speech API 流式传输音频
- python - Python/Numba/@jit:在使用返回值作为参数的递归函数中避免全局变量