Detailed React event

learning target

  • React event knowledge

React event features

  • Naming rules for bound events: camel case naming
  • Pass in a function instead of a string.
<button onClick={this.sendData}>发送数据 </button>

Event object: The event object returned by React is the native event object of the agent point. If you want to view the specific value of the event object, you must directly output the properties of the event object.

Native: To prevent the default behavior, just return false. The organizational default behavior in React must use e.preventDefault()
 

Example one  e.preventDefault()

import React, { Children } from 'react';
import ReactDOM from 'react-dom';
class ParenetCom extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <div>
          <form action="http://www.baidu.com">
            <div className="child">
                <h1>hello world</h1>
                <button onClick={this.parentEvent}>提交</button>
            </div>
          </form>
      </div>
    )
  }
  parentEvent = (e) => {
    e.preventDefault()
    //return false
  }
}
ReactDOM.render(
  <ParenetCom />, // 渲染父元素
  document.querySelector('#root') //寻找文件对象
)

Example 2 Arrow function

import React from 'react';
import ReactDOM from 'react-dom';
class ParenetCom extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <div>
          <button onClick={this.click('123')}>提交</button>
      </div>
    )
  }
  click = (e) => {
    console.log(e)
  }
}
ReactDOM.render(
  <ParenetCom />, // 渲染父元素
  document.querySelector('#root') //寻找文件对象
)

Loading the page http://localhost:3000/  prints 123 without clicking the button, and clicking the button does not work. The React event requires a function to be passed in, but the result of "this.click('123')}" is just a value, not a function. Can pass arrow function (pass in anonymous function)

Event e is usually placed at the end of the parameter as the last parameter.

Guess you like

Origin blog.csdn.net/A_bad_horse/article/details/105568310