React Native V: gestures

Source: Internet
Author: User


First, touchable gestures1.React Native provides 4 components to do this, specifically as follows:touchablehighlight: Highlight Touch, when the user clicks, will produce a highlight effect;Touchablenativefeedback:touchableopacity: Transparent touch, when the user clicks, the clicked component will not appear any visual changes;touchablewithoutfeedback: No feedback touch, when the user clicks, the clicked component will not have any visual changes;2. With these 4 components, we can apply a partial binding on the touch event and support the method:onpress:Onpressin:onpressout:onlongpress:3. Below we demonstrate with an example, the relevant code implementation:Index.android.js File:
 
Import React, {
  ...
  TouchableHighlight,
} from ‘react-native’;

Class AwesomeProject extends Component {
  Show(text) {
    Alert(text);
  }
  //Implementation of gesture related events
  onPressIn(){
    This.start = Date.now()
    Console.log("press in")
  }
  onPressOut(){
    Console.log("press out")
  }
  onPress(text){
    Console.log("press")
    Alert(text);
  }
  onLonePress(){ AppRegistry,
    Console.log("long press " (Date.now()-this.start))
  }
  Render() {
    Return(
      <View style={styles.container}>
        //TouchableHighlight package binds the components of the Touch gesture and implements 4 events supported
        <TouchableHighlight style={styles.touchable} onPressIn={this.onPressIn} onPressOut={this.onPressOut}
          onPress={this.onPress.bind(this, ‘clicked? ‘)} onLongPress={this.onLonePress}>
          <View style={styles.button}></View>
        </TouchableHighlight>
      </View>
    )
  };
}
Var styles = StyleSheet.create({
  Container: {
    Flex: 1,
    justifyContent: ‘center’,
    alignItems: ‘center‘,
    backgroundColor: ‘#F5FCFF‘,
  },
  Button:{
    Width: 200,
    Height: 200,
    borderRadius: 100,
    backgroundColor: ‘red‘
  },
  Touchable: {
    borderRadius: 100
  },
});
AppRegistry.registerComponent(‘AwesomeProject‘, () => AwesomeProject);
4. Click, we see the specific operating effect as follows:
5. We use the debug mode to study the conditions and sequence of the next 4 gestures;shake the phone, choose Debug JS;
Open the Chrome browser, after the http://localhost:8081/debugger-ui of the Debug page, select Develop tool, click the button on the phone to see the browser consoleOutput Content pressin->longpress->pressout;
second, the gesture response life cycle1. For most applications, with the above 4 touch* components, the user's gestures can be responded to with 4 press events. However, for more complex interactions, a gesture response system is also used;2. The basic unit of the response gesture is responder, specifically the view component, and any view component is a potential responder;3. A common view component becomes a responder that responds to gesture manipulation, as long as a few hand-response life-cycle methods can be set up, as follows:View.props.onStartShouldSetResponder: When the user starts to touch the screen, is willing to become the responder;View.props.onMoveShouldSetResponder: When each touch point begins to move, ask again if it responds to touch interaction;View.props.onResponderGrant: To start responding to touch events;View.props.onResponderReject: The responder now has another person, and for the time being will not be delegated, another arrangement;View.props.onResponderMove: The user is moving the finger on the screen;View.props.onResponderRelease: End of touch operation Trigger;View.props.onResponderTerminationRequest: There are other components requesting replacement of the responder, the current View is decentralized;View.props.onResponderTerminate: The right to respond has been surrendered;4. A responder can exist at the same time in a react native application, with the following specific response steps:the user "activates" a responder by touching or swiping, View.props.onStartShouldSetResponder and View.props.onMoveShouldSetResponder Both methods, if true, the view responds to touch or swipe gestures to be activated; If the component is activated, the View.props.onResponderGrant method is called, usually to change the background or transparency of the building, indicating that the component has been activated;Next, the user begins to swipe the finger, at which point the View.props.onResponderMove method is called;when the user's finger leaves the screen, the View.props.onResponderRelease method is called, and the component restores the style before the touch, such as the background color and the transparency before the restoration, to complete a gesture operation;Normal process: Release (end event), move--, response touch or move gesture, grant (activated);
5. Below we demonstrate with an example, the relevant code is as follows:index.android.js File
 6. The operating effect is as follows, OnClick is not clicked, click is clicked, and the console output log is followed:


Note: If you run Demode, the error message is as follows:
Create the component using var awesomeproject = React.createclass (); third, gesture event delivery1.onStartShouldSetResponder in Onmoveshouldsetresponder is called in the form of bubbling, that is, the deepest nesting node is called first;2. When multiple view returns true at the same time in Shouldsetresponder, the bottom view will take precedence over "seizure of power";3. But sometimes a parent view wants to be a responder first, and we can use the "capture period" to resolve it. The response system first performs a "capture period" from the bottom of the component before it bubbles, triggering the On*shouldsetrespondercapture series event. Therefore, if a parent view wants to block the component from becoming a responder at the start of the touch, it should handle the Onstartshouldsetrespondercapture event ice returns a true value;View.props.onStartShouldSetResponderCapture: (evt) =>true;View.props.onMoveShouldSetReponderCapture (evt) =>ture;
4. Below we will demonstrate with an example, the implementation code is as follows:Index.android.js File:
import React, {
   … … 
} from ‘react-native‘;

var AwesomeProject = React.createClass({
  getInitialState(){
    return {
      bg: ‘white‘
    };
  },

  componentWillMount(){
    this._gestureHandlers = {
      onStartShouldSetResponder: () => true,
      onMoveShouldSetResponder: ()=> true,
      onResponderGrant: ()=>{
        this.setState({bg: ‘red‘})
      },
      onResponderMove: ()=>{
        console.log(123)
      },
      onResponderRelease: ()=>{
        this.setState({bg: ‘white‘})
      }
    }
  },

  render() {
    return(
      <View style={styles.container}>
        <View {...this._gestureHandlers} style={[styles.rect, {backgroundColor:this.state.bg}]}></View>
      </View>
    );
  }
});
var styles = StyleSheet.create({
     … … 
});
AppRegistry.registerComponent(‘AwesomeProject‘, () => AwesomeProject);
5. For example, click inside Square, external square corresponding event:  iv. evt Parameters1. Similar to the event parameters in Web development, each of these methods has an evt parameter that, during the event, each of the nativeevent properties of the EVT parameter represents the state of the gesture:nativeeventchangedtouches: The array of all changed touch events after the last event (that is, all moved touch points after the last event)identifier: The ID of the touch pointLocationx: The horizontal axis of the touch point relative to the parent elementLocationy: The ordinate of the touch point relative to the parent elementPageX: The horizontal axis of the touch point relative to the root elementPagey: The ordinate of the touch point relative to the root elementtarget: The element ID where the touch point residesTimestamp: The timestamp of the touch event, which can be used to calculate the movement speedtouches: A collection of all touch points on the current screen
Wu, Panresponder1. In addition to the corresponding system of gestures, React native also abstracts a set of Panresponder methods, which are more abstract and more convenient to use;2. When using Panresponder, the logic and flow of the corresponding gesture will be the same, only need to modify several method name parameters according to the document:The first parameter of the EVT;The second gesturestate, which contains more information in the process of gestures, is more common as follows:Dx/dy: Gesture to the present horizontal/vertical relative displacement;Vx/vy: Horizontal/Vertical velocity at this moment;The number of touches on the Numberactivetouches:reponder;3. Below we use Panresponder to implement the drag effect, the code is implemented as follows:index.android.js File:
Import React, {
  ...
  PanResponder,
} from ‘react-native’;


Var AwesomeProject = React.createClass({
  getInitialState(){
    Return {
      Bg: ‘white’,
      Top: 0,
      Left: 0
    }
  },
  componentWillMount(){
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: ()=> true,
      onPanResponderGrant: ()=>{
        //When the slide starts, get the top left coordinate of the rectangle and set the background to red.
        This._top = this.state.top
        This._left = this.state.left
        this.setState({bg: ‘red‘})
      },
      onPanResponderMove: (evt,gs)=>{
        Console.log(gs.dx+‘ ‘+gs.dy)
        / / As the gesture slides, the corresponding position of the rectangle is changed
        this.setState({
          Top: this._top+gs.dy,
          Left: this._left+gs.dx
        })
      },
      onPanResponderRelease: (evt,gs)=>{
        / / After the event is over, restore the background to white
        this.setState({
          Bg: ‘white’,
          Top: this._top+gs.dy,
          Left: this._left+gs.dx
        })}
    })
  },
  Render: function() {
    Return (
      <View style={styles.container}>
        / / Set the gesture event processing object
        <View{...this._panResponder.panHandlers} style={[styles.rect,{
            "backgroundColor": this.state.bg,
            "top": this.state.top,
            "left": this.state.left}]}>
        </View>
      </View>
    );
  }
});
Var styles = StyleSheet.create({
  Container: {
    Flex: 1,
    //The starting rectangle is in the middle and dragged to the lower area
    justifyContent: ‘center’,
    alignItems: ‘center‘,
    backgroundColor: ‘#F5FCFF‘,
  },
  Rect: {
    ...
  }
});
AppRegistry.registerComponent(‘AwesomeProject‘, () => AwesomeProject);
6 Run the demo as follows, because you can only upload pictures, unable to demonstrate animation, the style of the rectangle in the middle, the picture dragged to the bottom:


React Native V: gestures


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.