【问题标题】:React Native TypeScript error: Property 'calcYOffset' does not exist on type 'ScrollView'React Native TypeScript 错误:“ScrollView”类型上不存在属性“calcYOffset”
【发布时间】:2020-04-15 16:45:10
【问题描述】:

我有一个ScrollView 的引用:

const childRef = React.useRef<null | ScrollView>(null);

<ScrollView
  onScroll={() => {
    childRef.current?.calcYOffset();
  }}

但是calcYOffset 给了我这个错误:

TS2339:“ScrollView”类型上不存在属性“calcYOffset”。

ref 附加在子组件中:

const containerViewRef = React.useRef<View>(null);

React.useImperativeHandle(ref, () => ({
      calcYOffset: () => {
        containerViewRef.current?.measure(
          (
            x: any,
            y: any,
            width: any,
            height: any,
            pageX: any,
            pageY: React.SetStateAction<number>,
          ) => {
            setViewYPosition(pageY);
          },
        );
      },
    }));

【问题讨论】:

  • 你在哪里附加myRefchildRef从哪里来,你在哪里定义calcYOffset
  • @MarekLisik 我更新了我的问题。
  • 您能否还显示childRef 的定义位置以及将其分配给组件的位置?
  • @MarekLisik 抱歉,我的问题有误,我已再次更新。
  • 你在哪里分配你的 refs 给组件呢?应该有一个例如。 。也许为上下文发布更多代码(至少包括定义组件和引用的位置,分配引用的位置,使用引用的位置等)

标签: typescript react-native


【解决方案1】:

打字稿错误是由const childRef = React.useRef&lt;null | ScrollView&gt;(null); 引起的,而不是&lt;null | ScrollView&gt;,您应该指定自定义组件的类型(使用useImperativeHandle 的组件)。你可以这样做:

type Handles = {
  calcYOffset: () => void;
}

type Props = { ... your custom component props };

const CustomComponent: React.RefForwardingComponent<Handles, Props> = // your component

// then usage:
const childRef = React.useRef<CustomComponent>(null);

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 2022-01-04
    • 2022-07-08
    • 2023-02-21
    • 2021-10-12
    • 2019-04-12
    • 2020-07-09
    • 2019-10-20
    • 2021-09-26
    相关资源
    最近更新 更多