【发布时间】:2017-08-02 20:51:20
【问题描述】:
我使用一个 FlatList 和一个后续的 ListHeaderComponent 作为我屏幕的根组件。我不希望它的顶部在滚动时弹跳,但我想保持底部弹跳以达到 UX'n'feel 的目的,因为 FlatList 支持无限滚动。 有什么想法吗?
【问题讨论】:
标签: react-native react-native-listview react-native-flatlist react-native-scrollview
我使用一个 FlatList 和一个后续的 ListHeaderComponent 作为我屏幕的根组件。我不希望它的顶部在滚动时弹跳,但我想保持底部弹跳以达到 UX'n'feel 的目的,因为 FlatList 支持无限滚动。 有什么想法吗?
【问题讨论】:
标签: react-native react-native-listview react-native-flatlist react-native-scrollview
一种解决方案是监听scroll 事件并检查是否应启用从ScrollView 继承的the bounces prop。请注意,我个人认为这个解决方案有点矫枉过正,但它可以按预期工作。
您可以在以下 URL 找到一个完整的工作示例:https://snack.expo.io/SkL-L0knZ。您可以直接在浏览器中预览,也可以在移动设备上使用Expo app 进行试用。
这是结果(忘记延迟,因为这是在浏览器中捕获的):
这里是相关的源代码:
export default class App extends Component {
constructor (props) {
super(props);
this.state = { bounces: false };
this.renderHeader = this.renderHeader.bind(this);
this._onScroll = this._onScroll.bind(this);
}
_onScroll (event) {
const scrollPosition = event && event.nativeEvent && event.nativeEvent.contentOffset && event.nativeEvent.contentOffset.y;
let newBouncesValue;
if (scrollPosition < viewportHeight / 3) {
newBouncesValue = false;
} else {
newBouncesValue = true;
}
if (newBouncesValue === this.state.bounces) {
return;
}
this.setState({ bounces: newBouncesValue });
}
renderHeader () {
const { bounces } = this.state;
const style = [
styles.header,
{ backgroundColor : bounces ? 'darkseagreen' : 'firebrick'}
];
return (
<Text style={style}>{ bounces ? 'CAN BOUNCE' : "WON'T BOUNCE"}</Text>
);
}
renderItem ({item}) {
return (
<Text style={styles.row}>{item.key}</Text>
);
}
render() {
return (
<View style={styles.container}>
{ this.renderHeader() }
<FlatList
data={DUMMY_DATA}
renderItem={this.renderItem}
onScroll={this._onScroll}
bounces={this.state.bounces}
scrollEventThrottle={16}
/>
</View>
);
}
}
【讨论】: