首页 > 解决方案 > 使用来自将 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 错误,很多必需的道具都丢失了。

我猜我没有正确指定导出接口,但是正确的方法是什么?

标签: reactjstypescriptreact-nativereact-hooks

解决方案


推荐阅读