【问题标题】:ScrollView RTL in react nativeScrollView RTL 在本机反应
【发布时间】:2017-04-23 12:23:06
【问题描述】:
以下代码是我在react native 项目中的ScrollView:
<ScrollView
ref={(scrollView) => { this._scrollView = scrollView; }}
horizontal={true}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
directionalLockEnabled={true}
bounces={false}
scrollsToTop={false}
>
现在它从左到右移动,第一次加载时它如何从右到左移动?
【问题讨论】:
标签:
reactjs
react-native
scrollview
【解决方案1】:
对于RTL 设置,您应该编写如下示例的代码:
import React, { useRef } from 'react';
import { ScrollView, StyleSheet } from 'react-native';
const RTLScrollView = () => {
const scrollRef = useRef();
const scrollToEnd = () => scrollRef.current.scrollToEnd({ animated: false });
return (
<ScrollView
horizontal
ref={scrollRef}
showsHorizontalScrollIndicator={false}
onContentSizeChange={scrollToEnd}
contentContainerStyle={styles.contentContainerStyle}
>
~~~
~~~
~~~
</ScrollView>
);
}
const styles = StyleSheet.create({
contentContainerStyle: {
flexDirection: 'row-reverse'
}
});
export default RTLScrollView;
提示:我不使用您的其他ScrollView 设置,如bounces={false},如果您愿意,请将其放入您的代码中,我的答案只是一个示例。
【解决方案2】:
我必须构建一个带有 RTL 滚动的自动完成功能。事实证明这很棘手,因为滚动到结束的解决方案导致了很多闪烁。我发现制作 RTL 的最佳方法是使用变换样式。如果您使用变换,那么将变换应用于列表中的每个项目也很重要。否则,您将拥有镜像文本。如果您想反转顶部/底部,此解决方案也适用,只需更改变换 scaleY 而不是 x。
这是我的滚动视图:
const renderList = () => {
return itemList.map(item => (
<Item
key={item.id}
address={item}
style={{ transform: [{ scaleX: -1 }] }}
/>
));
};
....
<ScrollView
contentContainerStyle={styles.scrollViewContentContainer}
horizontal
keyboardShouldPersistTaps="always"
ref={scrollView}
style={styles.scrollView}
>
{renderList()}
</ScrollView
这里是对应的ScrollView样式:
const styles = StyleSheet.create({
scrollView: {
marginRight: 10,
transform: [{ scaleX: -1 }]
},
scrollViewContentContainer: {
flexGrow: 1,
justifyContent: 'flex-end',
}
});
【解决方案3】:
正如@SlashArash 提到的,您可以使用react-native-invertible-scroll-view。
这是一个例子:
import React, { Component } from 'react';
import { View, Text, ScrollView} from 'react-native';
import InvertibleScrollView from 'react-native-invertible-scroll-view';
export default class Demo extends Component {
constructor(props) {
super(props);
this.scrollView = null;
}
render() {
let categories = ['one', 'two'];
categories = categories.map((category, index) => {
return (
<Text>{category}</Text>
)
});
return (
<View style={{
flex: 1,
}}>
<InvertibleScrollView inverted
ref={ref => { this.scrollView = ref }}
onContentSizeChange={() => {
this.scrollView.scrollTo({y: 0, animated: true});
}}
horizontal={true}
showsHorizontalScrollIndicator={false}
>
{categories}
</InvertibleScrollView>
</View>
)
}
}
【解决方案5】:
这确实是 React Native 中一个恼人的 Bug,ScrollView+RTL=Silly Bug。
虽然你可以适应多种技巧,但我这样做是为了克服这个错误:
- 我反转了我正在使用的数据数组。
- 用于:onContentSizeChange 事件处理程序来触发
ScrollView 上的 scrollToEnd({ animated: false }) 函数