您能看看我在 ScrollView 配置中缺少什么吗? 我正在尝试创建一个 ScrollView 动画,起始卡片子项偏移设备宽度的一半,然后当用户滚动时,它应该对齐中心, ScrollView 子项的其他其余部分也应该对齐
基本上所有子项在滚动时都应居中对齐。此外,第一个子项应从设备宽度的末尾开始。
progress so far -> https://snack.expo.io/@sefeniyuk/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'
}
});
最佳答案
您可以在功能组件中使用 react 状态 Hook 。您可以为起始滚动位置指定宽度,或者最好的方法是使用
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>
);
}
关于react-native - React-Native ScrollView 与自定义起始位置的中心对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815989/