reactjs - 如何让类型检查与 React forwardRef 一起使用
问题描述
我在使用 forwardRef 时无法进行类型检查。我的代码如下:
零件:
export interface Props {
label?: string;
callback: () => void;
}
export const _Button = (props: Props) => {
return (
<div>
<p>test</p>
</div>
);
};
export const Button = React.forwardRef((props, ref) => {
return <_Button { ...props } forwarded={ref} />
});
组件用法:
export const App = () => {
return (
<div>
<h1>Application</h1>
<Button label="foo" />
</div>
);
};
您可以看到我没有传递所需的回调道具,但打字稿没有看到问题。以下是我尝试过的,但我仍然无法进行类型检查。
export interface Props {
label?: string;
callback: () => void;
}
export const _Button = (props: Props) => {
return (
<div>
<p>test</p>
</div>
);
};
export const Button = React.forwardRef<HTMLButtonElement, Props>((props: Props, ref) => {
return <_Button { ...props } forwarded={ref} />
});
任何帮助,将不胜感激。谢谢。
添加图像以响应答案 1 和 2。这是我预计会遇到的打字稿错误。
解决方案
我假设你想做这样的事情:
import React, { FC, forwardRef, ForwardedRef, createRef } from 'react'
export interface Props {
label?: string;
callback: () => void;
forwardedRef: ForwardedRef<HTMLDivElement>
}
export const _Button: FC<Props> = (props: Props) => {
return (
<div ref={props.forwardedRef}>
<p>test</p>
</div>
);
};
export const Button = forwardRef<
HTMLDivElement,
Omit<Props, 'forwardedRef'>
>((props, ref) => <_Button {...props} forwardedRef={ref} />);
export const App = () => {
const ref = createRef<HTMLDivElement>();
return (
<div>
<h1>Application</h1>
<Button ref={ref} label="foo" callback={() => null} />
</div>
);
};
在这里您可以找到有关 refs 的文档。
推荐阅读
- kotlin - Kotlin 中的 HelloWorld 给出错误“找不到或加载主类”
- javascript - 我可以在 Angularfire 中有 2 个数据库引用吗
- wordpress - 帖子类型中的事件日期
- javascript - 条件为假,但仍执行
- c - 如何以最简单的方式使用 scanf() 引入多个字符串?
- rest - Netsuite - REST API - 使用基于令牌的身份验证 (TBA) 进行查询 - (在 Python 中)
- azure - 使用哪些 azure 服务来通知某事已完成?
- sql - 我需要从表中已检索到的列中检索一列
- algorithm - prometheus 是否保证基础设施时序数据的持久性?
- react-native - React Native KeyboardAvoidingView 立即隐藏