The React newbie village

methods

Let’s look at how to add methods to components. Methods can be bound to events such as Submit, Click, and change.

React events

Notice that React changes the case of events. The text on is appended to the event name. There are also events that use hump nomenclature. A typical React event is named:

on

What happens is that the text on is appended to the event name. In addition, case changes the name so that the event name is capitalized. Basically imagine events in React like this:

on<Event name>
Copy the code

Here are some common event names:

The event name The naming of the React
click onClick
change onChange
submit onSubmit

Hope you understand 🙂

Bind event & event handling methods

React namespaces can bind events and methods. Here is an example of a class component-based binding:

<Component onClick={this.handler}>
Copy the code

Class-based components and function-based components look slightly different. Let’s introduce the former first:

class Element extends React.Component {
  constructor(props) {
    super(props);
    this.clicked = this.clicked.bind(this);
  } 

  clicked() {
    console.log('clicked');
  }

  render() {
    return (
      <button onClick={this.clicked}></button>)}}Copy the code

Note:

  • Constructor, a line of code that binds the methods Clicked and this. This can be implemented in several ways:

    this.clicked = this.clicked.bind(this);
    Copy the code

    The binding methods Clicked and this are required. When a component method clicked() accesses properties, for example:

    clicked() {
     console.log(this.props.someAttribute);
    }
    Copy the code

    If the binding is successful, the value of someAttribute is printed. If the binding is not successful, an error is reported.

  • In JSX, binding can be done as follows:

    <button onClick={this.clicked}></button>
    Copy the code

    With the constructor binding, we can use this.linked directly, otherwise this would not have the linked method.

There are two other binding methods for Class components

So far, we’ve used statements like handler.bind(this) to bind events and methods, but that doesn’t look very elegant and requires binding for each method.

Is there a better way? There are actually two other options available:

  • Using anonymous functionslambdacall. InJSXInsert the arrow function into the expression
  • Declare a method as a field in a class

Use anonymous function calls

Let’s see how to use the arrow function in the tag:

class Element extends React.Component {
  constructor() {
    super(a); } state = {str: 'test'
  }

  clicked(evt) {
    console.log('clicked ' + this.state.str);
  }

  render() {
    return (
      <button onClick={(evt)= > this.clicked(evt)}></button>)}}Copy the code

Let’s find this row:

<button onClick={(evt) = > this.clicked(evt)}></button>
Copy the code

Let’s see how it compares to the first way, here’s the first way:

onClick={this.clicked}
Copy the code

This is done using the arrow function:

onClick={(evt) = > this.clicked(evt)}
Copy the code

Using the arrow function eliminates the need for binding in the constructor. We can also pass the evt event argument to the callback function when we use the arrow function, as well as other arguments:

render() {
    return (
      <button onClick={(evt)= > this.clicked(evt, 'left')}></button>
      <button onClick={(evt)= > this.clicked(evt, 'right')}></button>
      <button onClick={(evt)= > this.clicked(evt, 'top')}></button>
      <button onClick={(evt)= > this.clicked(evt, 'down')}></button>)}Copy the code

In the above example, we pass four different arguments left, right, top, and down to the bound function. Event EVt is the first parameter, custom parameter is the second parameter.

Declare a method as a field in a class

// Note: this is experimental syntax.

Let’s demonstrate another method:

class Element extends React.Component {

  constructor() {
    super(a);//this.clicked = this.clicked.bind(this);
  }

  state = {
    str: 'test'
  }

  clicked = () = > {
    console.log('clicked ' + this.state.str);
  }

  render() {
    return (
      <button onClick={this.clicked}></button>)}}Copy the code

> < span style = “max-width: 100%; clear: both

Note the comparison to the previous method declaration, which is old:

clicked() {
  console.log('clicked ' + this.state.str);
}
Copy the code

Here’s the new one:

clicked = () = > {
  console.log('clicked ' + this.state.str);
}
Copy the code

This is the preferred way to declare methods in a class.

Function components bind event methods

Binding event methods in function components is slightly different and we don’t need to consider this:

import React from 'react'

const AComponent = (props) = > {
  function handler(evt) = >{
    console.log('clicked'); 
  }

  return (
    <div>
      <button onClick={handler}></button>
    </div>)}export default AComponent;
Copy the code

As shown in the previous example, it is easier to bind event methods in function components.

case

  1. Git Clone

    git clone https://github.com/softchris/react-starter-project demo-methods
    cd demo-methods
    Copy the code

    The Start project uses webPack to configure the React project based on the tutorial

  2. Run the NPM install command to install dependencies:

    npm install
    Copy the code
  3. Add the methods.js file to the SRC directory and add the following:

    import React from 'react';
    
    class Method extends React.Component {
       constructor(props) {
         super(props)
         this.state = {
           direction: ' '
         }
       }
    
     changeDirection (evt, direction) {
       this.setState({
         direction
       })
     }
    
     render() {
         return (<React.Fragment>
           <div>Direction: {this.state.direction}</div>
           <div>
             <button onClick={(evt)= > this.changeDirection(evt, 'Top')}>Top</button>
             <button onClick={(evt)= > this.changeDirection(evt, 'Left')}>Left</button>
             <button onClick={(evt)= > this.changeDirection(evt, 'Right')}>Right</button>
             <button onClick={(evt)= > this.changeDirection(evt, 'Bottom')}>Bottom</button>
           </div>
         </React.Fragment>)}}export default Method;
    Copy the code

    The above example defines a class component in which the button click onClick event is bound to the changeDirection() method.

  4. Add a line to the index.js file to introduce:

    import Method from './Method';
    Copy the code
  5. Find the following code reactdom.render (with the following modifications:

    ReactDOM.render(
      <Method />.document.getElementById('app'));Copy the code
  6. Run project NPM start on terminal:

    npm start
    Copy the code
  7. Open your browser and visit **http://localhost:8080\**. View the results:

    See the directional state at the top. Select one of the buttons to update the status.

Reference code

👉 Check out this solution

summary

Describes how to add methods to components and then bind them to events.

  1. Bind methods in constructors for event handling.
  2. Using lambda arrow functions, you can skip bindings and pass values to methods.