reactjs - 使用来自将 ref 转发到 RN 组件的组件中的 ref.current 的打字稿错误
问题描述
新的 TypeScript 用户。我正在将一个 RN 项目转换为 TypeScript。到处使用钩子。我已经定义了一个组件 BitInput(它将引用转发到 TextInput),如下所示:
export interface Props {
value: number;
onChange?: (newValue: number) => void;
}
const BitInput: React.FC<Props> = forwardRef(
({ value, onChange }, ref: React.Ref<TextInput>) => {
return (
<TextInput
ref={ref}
onChange={onChange}
/>
);
};
我正在使用这个组件来构建一个 ByteInput 组件,如下所示:
import BitInput from './BitInput';
const BinaryInput: React.FC<Props> = ({ value, onChange }) => {
const ref: React.MutableRefObject<typeof BitInput | undefined>[] = [...Array(8)].map(() => useRef<typeof BitInput>() );
const handleKeyPress = (event) => {
switch (event.key) {
case 'ArrowRight':
for (let i = 0; i < ref.length; i++) {
if (ref[i].current?.isFocused() && i < ref.length - 1) {
ref[i + 1].current.focus();
break;
}
}
break;
}
};
render() {
return (
<View>
<BitInput
ref={ref[refIndex++]}
onKeyPress={handleKeyPress}
/>
</View>
..... 7 more BitInputs here .....
);
}
我正进入(状态TS2339: Property 'isFocused' does not exist on type 'FC '.
我也得到:
TS2322: Type 'MutableRefObject<FC<Props>>' is not assignable to type 'Ref<TextInput>'.
Type 'MutableRefObject<FC<Props>>' is not assignable to type 'RefObject<TextInput>'.
Types of property 'current' are incompatible.
Type 'FunctionComponent<Props>' is missing the following properties from type 'TextInput': isFocused, clear, measure, measureInWindow, and 19 more.
BitInput.tsx(11, 3): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'
我可以通过在 ref 声明中使用BitInput
而不是来解决这两个问题。typeof BitInput
但是现在我TS2749: 'BitInput' refers to a value, but is being used as a type here
开始了,在 JSX for BitCode 上我得到了 TS 错误,很多必需的道具都丢失了。
我猜我没有正确指定导出接口,但是正确的方法是什么?
解决方案
推荐阅读
- r - 尝试使用 tidyverse 和 ggplot 回答比较 r 中的组的描述性统计问题
- r - 包括下标/希腊字母/符号到ggplot x轴文本
- mysql - 查询以对索引列执行批量更新
- javascript - 如果脚本不在脚本文件中,用户是否有任何理由无法加载脚本?
- pandas - CSV/Pickle 文件太大而无法提交到 GitHub 存储库
- r - 创建索引将超过阈值的天数乘以 R 中的组超过阈值的数量
- google-sheets - 日期范围内的最大行数 - Google 表格
- if-statement - 电源自动化桌面中包含的多个条件
- javascript - 将数组元素添加到表单时出错:参数列表后未捕获 SyntaxError: missing )
- apache-kafka - 如何强制将现有的 Kafka 代理主题和分区复制到添加的 +2 个新代理?