javascript - 如何在 React Native 中将元素固定在滚动上?
问题描述
这是我到目前为止所拥有的视频https://drive.google.com/file/d/1tJMZfpe8hcqLcNMYiE-6pzwHX0eLofv1/view?usp=sharing
一旦 contentOffset.y 到达标题,我正在尝试修复“可用 3 个月”。类似于 a position: sticky
in css 会做的事情。
到目前为止,我想通过onScroll
Scroll View 组件中的 prop 执行此操作,但问题是,我已经有来自父子组件的动画 (Animated.Event),这意味着我这样做的唯一方法是通过但是,如果该选项设置为 false ,则执行此操作的listener
函数Animated.Event
会导致超级断断续续的动画。useNativeDriver
如果我将其设置为 true,那么整个事情将无法正常工作(它会崩溃)。错误是“onScroll 不是函数,它是 Animated.event 的实例”
所以,假设我们有两个组件,父组件Parent.js
和子组件(滚动视图)是ChildScrollView.js
滚动视图上ChildScrollView.js
已经有动画,但是我们需要在组件中添加更多,以处理无法处理Parent.js
的导航ChildScrollView.js
所以它的编码是这样的:
Parent.js
componentWillMount() {
const { navigation } = this.props
const { scrollY } = this.state
const bgColor = scrollY.interpolate({
inputRange: [HEADER_HEIGHT / 4, HEADER_HEIGHT / 2],
outputRange: ['transparent', 'rgb(255,255,255)'],
extrapolate: 'clamp',
})
const titleColor = scrollY.interpolate({
inputRange: [0, HEADER_HEIGHT / 2],
outputRange: ['transparent', colors.paragraphs],
extrapolate: 'clamp',
})
const titleMarginTop = scrollY.interpolate({
inputRange: [0, HEADER_HEIGHT / 2],
outputRange: [HEADER_HEIGHT, 0],
extrapolate: 'clamp',
})
navigation.setParams({
bgColor,
titleColor,
titleMarginTop,
})
}
onScroll() {
}
render() {
return (
<ChildScrollView
{...childProps}
onScroll={Animated.event([
{ nativeEvent: { contentOffset: { y: scrollY } } },
], {
useNativeDriver: false, // when I do this, it become super laggy, but setting it to true makes the app crash
listener: this.onScroll,
})}
>
<MakeMeFixedOnScroll>I could do this in css with "position: sticky"</MakeMeFixedOnScroll>
</ChildScrollView>
)
}
和孩子一样,
<Animated.ScrollView
{...props}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
{
useNativeDriver: false,
listener: event => {
if (onScroll) onScroll(event)
},
}
)}
scrollEventThrottle={16}
>
解决方案
我会使用 SectionList
<SectionList
renderItem={({item, index, section}) => (
<Text style={styles[item.type]}>{item.text}</Text>
)}
renderSectionHeader={({ section: { title } }) => (
title && <Text style={styles.sticky}>{title}</Text>
)}
sections={[
{ title: null, data: [{
type: 'heading', text: '133 Random Road'
}, {
type: 'heading', text: 'Donnybrook'
}, {
type: 'subtitle', text: 'Dublin 4'
}, {
type: 'title', text: 'From E1000/month'
}]
},
{ title: 'Available For 3 Month', data: [{
type: 'text', text: 'Beautiful for bedroom...'
}]
}
]}
stickySectionHeadersEnabled
/>
推荐阅读
- python - 用re替换文件中的单词
- haskell - How do you get the most recent version of Cabal for Haskell?
- apache-spark - 通过一列中的唯一值随机拆分 DataFrame
- mysql - MYSQL - Group Contact rows with records NOT IN
- php - php -> 定时 bash 脚本总是关闭
- swift - 快速将可测试代码与静态方法调度相结合
- excel - Excel AVERAGEIFS looking up ONE of the criteria columns
- javascript - 数据绑定按键事件在 div 上不起作用
- elasticsearch - 如何从 Elastic Search 中的日志文件中获取总执行时间?
- kubernetes - Kubernetes 构建集群时出错,找不到实用程序子网