2

您能否查看一下我在滚动视图配置中缺少的内容。我正在尝试创建一个滚动视图动画,其起始卡子偏移量为设备宽度的一半,然后当用户滚动时,它应该对齐中心,其他其余的滚动视图子也应该对齐

基本上所有的孩子在滚动时都应该居中对齐。第一个孩子也应该从设备宽度的末尾开始。

到目前为止的进展-> https://snack.expo.io/@sefiniyuk/scrollview-alignment

谢谢你。

import * as React from 'react';
import { Text, View, StyleSheet, ScrollView, Dimensions, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';

const { width } = Dimensions.get('window');
const cardPaddingHorizontal = 2;
const cardWidth = width - cardPaddingHorizontal * 2;
const cardleftOffset = width - cardWidth / 3.5;
const initialCardShown = width - cardleftOffset;

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <ScrollView         
          horizontal
          showsHorizontalScrollIndicator={false}
          scrollEventThrottle={1}
          style={styles.style}
          contentContainerStyle={styles.contentContainerStyle}
          snapToAlignment="center"
          decelerationRate="fast"
        >
          {[1, 2, 3, 4].map((num, i) => {
            return (
              <TouchableOpacity key={i} style={styles.card}>
                <View style={styles.content}>
                <Text style={styles.text}>{num}</Text>
                </View>
              </TouchableOpacity>
            );
          })}

        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
    contentContainerStyle: {
    width: cardWidth * 4
  },
  style: {
    paddingLeft: cardleftOffset
  },
  card: {
    backgroundColor: 'red',
    width: cardWidth,
    height: cardWidth,
    margin: cardPaddingHorizontal,
    elavation: 10
  },
  content: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  text: {
    fontSize: 40,
    color: 'white'
  }
});
4

1 回答 1

1

您可以在功能组件中使用反应状态挂钩。您可以为起始滚动位置指定宽度,或者最好的方法是使用

scrollViewRef.current.scrollToIndex({ index: "index-of-item" })

import React, {useRef} from 'react'
    
const App = () => {

   const scrollViewRef = useRef();

   return (
      <ScrollView horizontal={true} ref={scrollViewRef} 
       onContentSizeChange= 
       {() => scrollViewRef.current.scrollTo({x: giveWidth, y: 
       giveHeight, animated: true})}>
       .
       .
       .
       .
      </ScrollView>
   );
}

于 2021-12-31T07:59:29.557 回答