react-native - React-Native ScrollView 与自定义起始位置的中心对齐
问题描述
您能否查看一下我在滚动视图配置中缺少的内容。我正在尝试创建一个滚动视图动画,其起始卡子偏移量为设备宽度的一半,然后当用户滚动时,它应该对齐中心,其他其余的滚动视图子也应该对齐
基本上所有的孩子在滚动时都应该居中对齐。第一个孩子也应该从设备宽度的末尾开始。
到目前为止的进展-> 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'
}
});
解决方案
您可以在功能组件中使用反应状态挂钩。您可以为起始滚动位置指定宽度,或者最好的方法是使用
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>
);
}
推荐阅读
- python-3.x - 尝试使用服务帐户读取 GMAIL 时出现错误代码 400
- javascript - D3.js 径向条形图,条形为线
- html - 为什么这个登录模板没有正确显示?
- inkscape - Inkscape:如何将上标和下标附加到同一个字符
- javascript - 单击下拉列表项不起作用 - Jquery
- flutter - 未处理的异常:处理后使用了 ChangeNotifier
- arrays - 如何使用usestate在特定索引中拼接或推送新元素?
- python-3.x - Docusign Webhook
- python - 如何删除具有最新日期和多个其他条件的行?
- python - 当我尝试将精灵添加到屏幕时,PyGame 滞后