如何在React Native中使元素固定在滚动上?

时间:2019-04-18 10:18:02

标签: javascript reactjs react-native react-animated

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

的视频

一旦ContentOffset.y到达标题后,我将尝试修复“ 3个月可用”。类似于CSS中的position: sticky会执行的操作。

到目前为止,我曾想过通过Scroll View Component中的onScroll prop来执行此操作,但问题是,我已经在父子组件中设置了动画(Animated.Event),这是唯一的方法对我来说,这是通过listener中的Animated.Event函数来完成的,但是如果useNativeDriver选项设置为false,则会产生超震撼的动画。

如果我将其设置为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}
        >

1 个答案:

答案 0 :(得分:0)

我会使用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
/>
相关问题