首页 > 解决方案 > 如何在 React Native 中将元素固定在滚动上?

问题描述

这是我到目前为止所拥有的视频https://drive.google.com/file/d/1tJMZfpe8hcqLcNMYiE-6pzwHX0eLofv1/view?usp=sharing

一旦 contentOffset.y 到达标题,我正在尝试修复“可用 3 个月”。类似于 a position: stickyin css 会做的事情。

到目前为止,我想通过onScrollScroll 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}
        >

标签: javascriptreactjsreact-nativereact-animated

解决方案


我会使用 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
/>

推荐阅读