React 的事件触发及事件绑定

一、事件触发

JSX与HTML中的语法比较:
1.事件触发在Html的写法是全部小写在JSX中是採用驼峰式命名法
2.呼叫函式由"action()"改为{this.action}

//html的按钮写法<button onclick="action()">  请按我</button>
//JSX的按钮写法<button onClick={this.action}>  请按我</button>

二、事件绑定

在事件中如果要使用到参数,就要绑定,没有绑定就会出现错误。
见图片

事件绑定的四种写法

1.在class中的constructor中绑定事件:

import React from "react";class ButtonTest extends React.Component {  constructor(props){      super(props);      this.handleEdit = this.handleEdit.bind(this);  //绑定  }  handleEdit(event) {    //事件函式参数event,透过这个方法可以得到当事件发生时,发生事件的元素上的各种资讯。     console.log('message',this.props);  }    render() {      return <button onClick={this.handleEdit}>送出</button>  }}export default ButtonTest;

2.在class中render中绑定事件

import React from "react";class ButtonTest extends React.Component {    handleEdit(event) {        console.log('message',this.props);        console.log('event',event);    }        render() {        return <button onClick={this.handleEdit.bind(this)}>送出</button>  //绑定的位置    }}export default ButtonTest;

3.使用箭头函数在 render 中绑定进行绑定

import React from "react";class ButtonTest extends React.Component {  handleEdit = (event) => {       console.log('message',this.props);   }      render() {       return <button onClick={this.handleEdit}>送出</button>   }}export default ButtonTest;

4.使用匿名函数(箭头函数)与在 render 中进行绑定

import React from "react";class ButtonTest extends React.Component {  handleEdit(event) {      console.log('message',this.props);      console.log('event',event);  }    render() {      return <button onClick={() => this.handleEdit(this)}>送出</button>  }}export default ButtonTest;

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章