Simple demonstration of React event processing

Keywords: Javascript React

html version:

<button onclick="activateLasers()">
  Activation button
</button>

react version

<button onClick={activateLasers}>
  Activation button
</button>

 

You cannot block the default behavior by returning false. You must explicitly use preventDefault

html version

< a href = "ා" onclick = "console. Log ('click the link '); return false" >
  Point me
</a>

react version

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('Link clicked');
  }
 
  return (
    <a href="#" onClick={handleClick}>
      //Point me
    </a>
  );
}

 

You don't usually need to use the addEventListener to add listeners to a DOM element that has already been created
You need to provide a listener when this element is initially rendered

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import PropTypes from 'prop-types';

class Toggle extends React.Component{
  constructor(props){
    super(props);

    this.state={
      toggle:true
    }

    this.toggleHandler=this.toggleHandler.bind(this);
  }

  //prevState yes React The first one. State(state) 
  toggleHandler(){
    this.setState(prevState=>({
      toggle:!prevState.toggle
    }))
  }
  
  render(){
    return(
      <button onClick={this.toggleHandler}>{this.state.toggle?'on':'off'}</button>
    )
  }
}

  ReactDOM.render(
    <div>
      <Toggle/>
    </div>,
    document.getElementById('example')
  );

serviceWorker.unregister();

Passing parameters to the event handler

How to transfer bind(this) of React click event?
You need to bind the parameters through the bind method. The first parameter points to this, and the second parameter is the parameter received by the event function at the beginning

Pass parameters to the listener function through bind mode, and the event object e should be next to the passed parameters

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import PropTypes from 'prop-types';

class Toggle extends React.Component{
  constructor(props){
    super(props);

    this.state={
      name:'cyy'
    }
  }

  //prevState yes React The first one. State(state) 
  preventPop(name,e){
    e.preventDefault();
    console.log(name);
  }
  
  render(){
    return(
      <button onClick={this.preventPop.bind(this,this.state.name)}>Block default behavior and print names</button>
    )
  }
}

  ReactDOM.render(
    <div>
      <Toggle/>
    </div>,
    document.getElementById('example')
  );

serviceWorker.unregister();

Posted by sevenfive on Mon, 13 Apr 2020 10:11:52 -0700