react事件绑定ES6写法

文章参考

  1. React.js中常用的ES6写法总结

案例说明

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

class Photegraph extends BaseComponent {
	// video 和 mediaStreamTrack 是Photegraph类的属性
    video;
    mediaStreamTrack;
	// 构造函数
	constructor (props) {
        super(props);
		// 给openPhoto方法的指针指向当前对象,在jsx中就不需要再使用bind指定对象了
        this.openPhoto = this.openPhoto.bind(this);
	}
	
	// react 对象生命周期函数,表示节点挂载之前执行的方法
    componentWillMount() {
        
    }

    // 利用canvas获取vedio中的图片,并在canvas中显示
    snapshootAction(){
        console.log("snapshootAction");
    }

    // 上传文件
    uploadFile(){
        console.log("uploadFile");
    }

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

    // 开启摄像头
    openPhoto(){
        console.log("openPhoto");
    }

    // 回退到上一个页面
    backPage(){
        console.log("backPage");
    }

    render () {
        return (
        <div>
            <NavBar
                mode="light"
                icon={<Icon type="left" />}
                onLeftClick={this.backPage}
            >拍照识别</NavBar>
            <div style={{padding:"0px 16px"}}>
                <Button type="primary" onClick={this.openPhoto}>打开摄像头</Button>
                <Button type="primary" onClick={()=>this.snapshootAction()}>截图</Button>
                <Button type="primary" onClick={()=>this.closePhoto()}>关闭摄像头</Button>
                <Button type="primary" onClick={this.uploadFile.bind(this)}>上传文件</Button>
            </div>
        </div>
        );
    }

}

export default Photegraph;

在JSX中定义函数的写法

  1. 函数名一定是驼峰命名法,例如onClick
  2. 函数一定要用{}包裹起来,表示是一个变量或者函数名

不能使用“函数名()”,后面的括号表示执行函数,因此使用()=>this.closePhoto()箭头函数,返回定义的函数

  1. onLeftClick={this.backPage},直接指明函数名字,后面没有括号,也没有传递this对象和参数
  2. onClick={this.uploadFile.bind(this)} 把方法内部的对象改为this,传递上下文

猜你喜欢

转载自blog.csdn.net/hbiao68/article/details/83580551
今日推荐