如何使用PanResponder使辅助<view>进入主视图?

时间:2018-11-11 22:03:49

标签: ios react-native view

安装视图后,我希望第二个视图位于主视图右侧的屏幕上

当用户平移向左滑动 时,次视图应跟随平移并最终覆盖主视图。 (如Instagram相机)

我已经建立了基本结构,但是不确定如何完成<Animated.View>部分。例如,是否将平移处理程序放置在主视图或辅助视图上?我不希望辅助视图包含主视图上的任何交互。

import React from 'react';
import { PanResponder, Animated, Dimensions, StyleSheet, Text, View } from 'react-native';
const winWidth = Dimensions.get('window').width
const winHeight = Dimensions.get('window').height

class Main extends React.Component {
    constructor(props){
        super(props);
    }
    translateX = new Animated.Value(0);
    panResponder = PanResponder.create({
        onMoveShouldSetPanResponderCapture: (e, gs) => {
            return gs.dx < 0 //allow left only
        },
        onPanResponderMove: (e, gs) => { 
            if(gs.dx < 0) { 
                Animated.event([null, {dx: this.translateX}])(e, gs) 
            }
        },
        onPanResponderRelease: (e, {vx, dx}) => {
            //Secondary View should now cover the main View
        },
        onPanResponderTerminationRequest: (e, gs) => {
            return false 
        },
        onPanResponderTerminate: (e, {vx, dx} ) => {
        },
    })
    render(){
        return(
            <View style={{styles.main}}>
                <View style={{styles.secondary}}></View>
                <View><Text>Other components will be displayed</Text></View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    main:{
        flex:1,
        flexDirection:'column',
        backgroundColor: '#ffffff'
    },
    secondary:{
        width: winWidth,
        height: winHeight,
        backgroundColor: 'red',
        position: 'absolute',
        top:0,
        left:winWidth, //start off screen
    },
})

1 个答案:

答案 0 :(得分:1)

我不确定这是否是您想要的,但是我的方式是在覆盖整个屏幕的Animated.View组件内嵌套两个View。

<Animated.View style={[this.position.getLayout(), {display: 'flex', flex: 1, flexDirection: 'row'}]} {...this.panResponder.panHandlers}>
    <View style={{width: '100%', height: '100%', backgroundColor: 'yellow'}}>
        <Text>
            This is the Main view
        </Text>
    </View>

    <View style={{ height: '100%', width: '100%', backgroundColor: 'red'}}>
        <Text>
            This is the invisible View
        </Text>     
    </View>
</Animated.View>
  • 视图中的样式是使每个覆盖全宽

  • 在Animated.View内部,我使用了数组符号来应用两种样式

  • this.position.getLayout()是给出Animated.View组件应位于的坐标/位置的

  • 另一个样式对象是,因此我们可以使用flexbox特别是设置

  • 来使子视图彼此相邻渲染。
  • 还将panHandlers附加到Animated.View

    constructor(props){
      super(props)
      position = new Animated.ValueXY()
    
      const panResponder = PanResponder.create({
          onStartShouldSetPanResponder: ()=> true,
          onPanResponderMove: (evt, gesture)=>{
              //Need to set theshhold and state.isOpen to determine direction here
              position.setValue({x: gesture.dx, y: 0})
          },
          onPanResponderGrant: ()=>{
              this.position.setOffset({x: this.position.x._value, y: 0})
              this.position.setValue({x: 0, y: 0})
          },
          onPanResponderRelease: ()=>{
              this.openOrClose()        
          }
      })
    
      this.state = {isOpen: false} 
      this.panResponder = panResponder
      this.position = position
    }
    
  • 我使用状态来监视视图应移至 this.state = {isOpen:false} 的位置,具体取决于可见的视图。

  • 要移动的功能主要是 position.setValue({x:gesture.dx,y:0}),它在触摸/平移仍处于活动状态时跟踪移动,而 > this.openOrClose(),当释放触摸/平移时会调用它。

  • openOrClose函数确定如何处理运动,主要逻辑应在此处。我只是做了一个简单的案例,在此示例中未包含任何threshHold。

  • 要了解panHandlers,我建议您阅读this article,因为它解释了 onPanResponderGrant 最佳的原因。

下面是工作组件的代码

import React, {Component} from 'react'
import {View, Text, Animated, PanResponder, Dimensions} from 'react-native'

const ScreenWidth = Dimensions.get('window').width

//Logic to flattenOffset required
export class Swipable extends Component{
	constructor(props){
		super(props)
		position = new Animated.ValueXY()

		const panResponder = PanResponder.create({
			onStartShouldSetPanResponder: ()=> true,
			onPanResponderMove: (evt, gesture)=>{
				//Need to set theshhold and state.isOpen to determine direction here
				position.setValue({x: gesture.dx, y: 0})
			},
			onPanResponderGrant: ()=>{
				this.position.setOffset({x: this.position.x._value, y: 0})
				this.position.setValue({x: 0, y: 0})
			},
			onPanResponderRelease: ()=>{
				this.openOrClose()		
			}
		})

		this.state = {isOpen: false} 
		this.panResponder = panResponder
		this.position = position
	}

	openOrClose = ()=>{
		this.position.flattenOffset()
		//determine where to move depending onState
		direction = this.state.isOpen ? 0 : -ScreenWidth

		Animated.spring(this.position, {
			toValue: {x: direction, y: 0}
		}).start(()=>{
			//Callback when animation is complete to show if open or closed
			this.setState((prevState)=>{
			 	return {isOpen: !prevState.isOpen}
			})
		})
	}

	render(){
		return(
			<Animated.View style={[this.position.getLayout(), {display: 'flex', flex: 1, flexDirection: 'row'}]} {...this.panResponder.panHandlers}>
				<View style={{width: '100%', height: '100%', backgroundColor: 'yellow'}}>
					<Text>
						This is the Main view
					</Text>
				</View>
				
				<View style={{ height: '100%', width: '100%', backgroundColor: 'red'}}>
					<Text>
						This is the invisible View
					</Text>		
				</View>
			</Animated.View>
		)
	}
}

我在Android模拟器上运行了以上代码,我确信它可以在ios上运行。如果有任何需要澄清或改进的地方,请告诉我