首页 > 解决方案 > How to describe the ScrollEvent type in React-Native(-Web) via typescript?

问题描述

I can't figure out how to describe the ScrollEvent type in React-Native-Web but I suppose the same is actual for the React Native?

To be honest, it's always a bit hard for me to correctly describe the Event types for the React native (and the standard React as well) because I haven't found any common documentation, etc. about it so I always used

In general, we can use the Generic Synthetic Event and we can pass the definition of the required type into this generic. I guess in my case it must be something like ScrollEvent but I don't have any idea what exactly should be located there?

I tried to use the standard React.SynteticEvent type however I received an error

Property 'contentOffset' doesn't exist on type Event

The code example

      onScroll={(e: React.SyntheticEvent) => {
        let y = 0;

        // the scroll data receives differently on mobile and web
        if (Platform.OS !== 'web') {
          // Property 'contentOffset' doesn't exist on type Event
          y = e.nativeEvent.contentOffset.y;
        } else {
          // Property 'target' doesn't exist on type Event
          y = e.nativeEvent.target.scrollTop;
        }

        if (inputLayout.scrollY !== y) {
          setInputLayout({
            ...inputLayout,
            scrollY: y,
          });
        }

        if (isFunction(onScroll)) {
          onScroll(e);
        }
      }}

Many thanks for any help/info/link to the documentation!

标签: reactjstypescriptreact-nativeeventsreact-native-web

解决方案


正确的接口Scroll EventUIEvent

import React, { UIEvent } from 'react';

onScroll={(e: UIEvent<HTMLDivElement>) => {

推荐阅读