react event binding ES6

Keywords: Web Development React Mobile

Article reference

  1. Summary of ES6 in React.js

Case description

import React from "react"
import { NavBar, Button, Icon } from "antd-mobile"

class Photegraph extends BaseComponent {
	// video and mediaStreamTrack are properties of the photographic class
    video;
    mediaStreamTrack;
	// Constructor
	constructor (props) {
        super(props);
		// The pointer to the openPhoto method points to the current object, and there is no need to use bind to specify the object in jsx
        this.openPhoto = this.openPhoto.bind(this);
	}
	
	// react object lifecycle function, which represents the method executed before the node is mounted
    componentWillMount() {
        
    }

    // Using canvas to get the pictures in vedio and display them in canvas
    snapshootAction(){
        console.log("snapshootAction");
    }

    // Upload files
    uploadFile(){
        console.log("uploadFile");
    }

    closePhoto(){
        this.mediaStreamTrack && this.mediaStreamTrack.stop();
    }

    // Turn on the camera
    openPhoto(){
        console.log("openPhoto");
    }

    // Back to previous page
    backPage(){
        console.log("backPage");
    }

    render () {
        return (
        <div>
            <NavBar
                mode="light"
                icon={<Icon type="left" />}
                onLeftClick={this.backPage}
            >Photo recognition</NavBar>
            <div style={{padding:"0px 16px"}}>
                <Button type="primary" onClick={this.openPhoto}>Turn on the camera</Button>
                <Button type="primary" onClick={()=>this.snapshootAction()}>screenshot</Button>
                <Button type="primary" onClick={()=>this.closePhoto()}>Turn off camera</Button>
                <Button type="primary" onClick={this.uploadFile.bind(this)}>Upload files</Button>
            </div>
        </div>
        );
    }

}

export default Photegraph;

Writing method of defining function in JSX

  1. Function names must be hump nomenclature, such as onClick
  2. A function must be wrapped with {} to represent a variable or function name

You cannot use "function name ()", and the parentheses after it indicate the execution function, so use the arrow function () = > this. Closephoto() to return the defined function

  1. onLeftClick={this.backPage}, directly indicating the function name, without parentheses, and without passing this object and parameters
  2. onClick={this.uploadFile.bind(this)} changes the object inside the method to this, passing the context

Posted by su1d on Thu, 12 Dec 2019 13:06:50 -0800