reactjs - 向下滚动时 react native 淡入右/左 View

标签 reactjs react-native

我在 ScrollView 中有 3 个 View,如何在向下滚动时向右或向左淡入每个 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 )

最佳答案

我已经为您创建了一个小示例,但是您当然需要对其进行微调,使其能够完全满足您的目的。

演示

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>

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

关于reactjs - 向下滚动时 react native 淡入右/左 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906604/

相关文章:

android - 如何使用单个导航文件将 Drawer Navigator 包含在 Tab Navigator 中的 Stack Navigator 中

react-native - 不要将 React Native 元素中的禁用输入灰显

ios - 重复的模块名称 : react-native

javascript - 如何检查深层嵌套的 Prop

javascript - 按钮输入类型提交不在 React 中使用 React Router 提交

javascript - react : Cannot Find module './WebpackMissingModule'

javascript - Prop 未动态更新

React-native-maps LocalTile 存储图 block

react-native - 响应 native 底部模式与水平滚动

javascript - 如何在单元测试环境中模拟 browserHistory?