滚动到本机反应

问题描述 投票:0回答:1

我正在寻找一种在单击 React 中的按钮时滚动到特定位置的方法。在React中使用scrollIntoView很容易,但在React Native中,没有什么是简单的,我找不到方法来做到这一点:/我尝试在ScrollViews上使用useRef和scrollTo,但它不起作用。

如果有人有任何建议,我会洗耳恭听。

 const scrollViewRef = useRef(null);
  const section3Ref = useRef(null);

  const scrollToSection = () => {
    if (scrollViewRef.current) {
      scrollViewRef.current.scrollTo({ y: 200});
    }
  };
return( <Architecture ref={scrollViewRef}>
        <Button title="Scroll to Section 3" onPress={scrollToSection} />
        <View ref={section3Ref}>
        <VeterinarianPet />
        </View>
         </Architecture>
)

我希望当我单击按钮时它会滚动到兽医部分

提前抱歉我的英语不好

这是我的组件架构

import React, { ReactNode } from "react";
import {
  
  ScrollView,
  SafeAreaView,
  View,
  Dimensions,
 
} from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import tw from "../../tw-rn";

interface ArchitectureProps {
  children: ReactNode;
  ref?: any;
}

/**
 * Architecture component allows scrolling in the page - Composant Architecture permettant de scroller dans la page
 * @param {object} children - Children components - Composants enfants
 * @returns {JSX.Element} - Architecture component allows scrolling in the page - Composant Architecture permettant de scroller dans la page
 */
const Architecture = ({ children ,ref }: ArchitectureProps) => {
  const { height } = Dimensions.get("window");
  return (
    <View>
      <SafeAreaView>
        <KeyboardAwareScrollView>
          <ScrollView
            nestedScrollEnabled
           ref={ref}
          >
            <View style={tw`pb-25`}>{children}</View>
          </ScrollView>
        </KeyboardAwareScrollView>
      </SafeAreaView>
    </View>
  );
};

export default Architecture;

react-native expo
1个回答
0
投票

我解决了我的问题!

const scrollViewRef = useRef(null);

  const scrollToPosition = (y) => {
    scrollViewRef.current?.scrollTo({ y, animated: true });
  };

  return (
    
      <ScrollView ref={scrollViewRef}>
        
        <Button title="Scroll to 500" onPress={() => scrollToPosition(800)} />
       
           
      </ScrollView>
      
  );
};

问题是我在“建筑”中的道具中传递了我的参考。只需更改滚动视图就可以了:)

谢谢你的回答

© www.soinside.com 2019 - 2024. All rights reserved.