0

我有两个组件-一个由滚动视图和一个在滚动时触发的函数组成,另一个包含一个页脚,我想在滚动时更改其高度。

带有 scrollView 的第一个组件是这样的——

const FOOTER_MAX_HEIGHT = 60;
const FOOTER_MIN_HEIGHT = 0;
const FOOTER_SCROLL_DISTANCE = FOOTER_MAX_HEIGHT - FOOTER_MIN_HEIGHT;
class Home extends React.Component {
  state= {
   scrollY: new Animated.Value(0),
  }

    onScroll = () => {
    console.log("scrolling");
    Animated.event([{ nativeEvent: { contentOffset: { y: this.state.scrollY }} }]);
  }

  renderFooter = () => {
    const footerHeight = this.state.scrollY.interpolate({
      inputRange: [0, FOOTER_SCROLL_DISTANCE],
      outputRange: [FOOTER_MAX_HEIGHT, FOOTER_MIN_HEIGHT],
      extrapolate: 'clamp',
    });
    return (
        <Footer
          footerHeight = {footerHeight}
        />
    );
  }

  render(){
    return(
     <View style={{flex: 1}}>
      <List onScroll={this.onScroll}/>
      {this.renderFooter()}
     </View>

    )
  }
}

在 list.js 中,我有一个带有这样的功能的滚动视图

class List extends React.Component{
  render(){
    return(
    <ScrollView onScroll={this.props.onScroll}>{this.renderScrollViewElements()}</ScrollView>
    )
  }
}


import React from 'react';
import { View, Animated } from 'react-native';
const styles = StyleSheet.create({
  navbarContainer: {
    backgroundColor: 'red',
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
  },
  menuContainer: {
    width: 80,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

    class Footer extends React.Component {

      render() {
        const { footerHeight } = this.props;

        return (
          <Animated.View style={[styles.navbarContainer, { height: this.props.footerHeight }]}>
            <View style={styles.menuContainer}>
               <Text>ABC</Text>
           </View>
          </Animated.View>
        );
      }
    }

此代码的问题在于页脚的高度恒定为 60。即使在滚动视图滚动时,它也不会更新。

4

1 回答 1

0

需要注意的一件事是使用动画 API 在标准“渲染”循环之外运行。这意味着,在您的 Home 组件中,当您的scrollY更新时,它不一定会调用render()方法。这意味着您的 footerHeight 道具将永远无法通过。

由于您的 Footer 是Animated.View,因此您应该将 footerHeight 作为具有高度的样式对象直接发送,因为无论是否调用 render() 都会更新 Animated 组件的样式。

renderFooter = () => {
const footerHeight = this.state.scrollY.interpolate({
  inputRange: [0, FOOTER_SCROLL_DISTANCE],
  outputRange: [FOOTER_MAX_HEIGHT, FOOTER_MIN_HEIGHT],
  extrapolate: 'clamp',
});
return (
      <Footer 
         style={{height: footerHeight}}>
      />
);
}
于 2018-03-12T06:46:51.630 回答