向下滚动反应原生淡化右/左视图

问题描述 投票:4回答:2

我在View有3个ScrollView,如何在向下滚动时每个View向右或向左淡化?

<ScrollView >
  <View>
    <Text>Fade Right View 1</Text>
  </View>

  <View>
    <Text>Fade Right View 2</Text>
  </View>

  <View>
    <Text>Fade Right View 3</Text>
  </View>
</ScrollView >

像这样:元素淡入滚动(https://codepen.io/annalarson/pen/GesqK

reactjs react-native
2个回答
4
投票

我已经为您创建了一个小例子,但当然您需要对其进行微调以完全发挥作用。

演示

gif

说明

我的例子包含两个组成部分。一个Fade组件和实际的ScrollView。淡化组件处理动画。通过滚动ScrollView触发动画淡入(请参阅handleScroll函数)。

淡化组件

class Fade extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: props.visible,
      visibility: new Animated.Value(props.visible ? 1 : 0),
    };
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.visible) {
      this.setState({ visible: true });
    }
    Animated.timing(this.state.visibility, {
      toValue: nextProps.visible ? 1 : 0,
      duration: 500,
    }).start(() => {
      this.setState({ visible: nextProps.visible });
    });
  }

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

    const containerStyle = {
      opacity: this.state.visibility.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 1],
      }), // interpolate opacity 
      transform: [
        {
            translateX: this.state.visibility.interpolate({
                inputRange: [0, 1],
                outputRange: [-20, 0],
            }), // interpolate translateX to create a fade in left/right
        },
      ],
    };

    const combinedStyle = [containerStyle, style];
    return (
      <Animated.View style={this.state.visible ? combinedStyle : containerStyle} />
    );
  }
}

ScrollView代码段

handleScroll(e) {
    if (e.nativeEvent.contentOffset.y > 50) { // you need to fine tune this value
      this.setState({ visible: true }); 
    }
  }


<ScrollView onScroll={(e) => this.handleScroll(e) } scrollEventThrottle={8}>
          <View style={{ backgroundColor: 'yellow', height: 200, marginTop: 10 }}/>
          <View style={{ backgroundColor: 'yellow', height: 200, marginTop: 10 }}/>
          <View style={{ backgroundColor: 'yellow', height: 200, marginTop: 10 }}/>
          <Fade style={{ backgroundColor: 'red', height: 200, marginTop: 10 }} visible={this.state.visible} />
</ScrollView>

我希望我的例子能让你了解如何实现预期的行为。


-1
投票

你可以像这样使用onScroll

<ScrollView onScroll={this.handleScroll} />

之后 :

handleScroll = (event: Object) => {
 console.log(event.nativeEvent);
 // You see {layoutMeasurement, contentOffset, contentSize} in nativeEvent
}

使用contentOffsetlayoutMeasurementcontentSize,你可以在React Native中重写Element Fade In on Scroll

© www.soinside.com 2019 - 2024. All rights reserved.