React gets input value and submits 2 methods examples

React gets input value and submits 2 methods examples

Method 1: Use the target event attribute of the Event object provided by DOM to obtain the value and submit it

import React from 'react';
 
class InputDemo extends React.Component{
  state = {
    InputValue : "", //input value in input box};
 
  handleGetInputValue = (event) => {
    this.setState({
      InputValue : event.target.value,
    })
  };
 
  handlePost = () => {
    const {InputValue} = this.state;
    console.log(InputValue,'------InputValue');
    //Perform submission operations here, such as sending dispatch, etc.};
 
  render(){
    return(
      <div>
        <input
          value={this.state.InputValue}
          onChange={this.handleGetInputValue}
        />
        <button onClick={this.handlePost}>Submit</button>
      </div>
    )
  }
}
 
export default InputDemo;

The <input /> and <button /> here are both HTML tags. Of course, you can also use Antd's <Input /> and <Button /> components, and the content inside remains unchanged.

First, define InputValue:" in the state at the top of the component, and write value={this.state.InputValue} in the <input /> below. If the onChange event is removed, then nothing can be entered in the input box at this time, because

React believes that all states should be controlled by React's state. As long as input controls such as <input />, <textarea />, and <select /> are set with a value, their values ​​will always be based on the set value. If the value has not been changed, the value will not change.

In React, setState is required to update the content of a component, so you need to listen to the onChange event of the input box, get the content of the input box, and update the InputValue of the state through setState, so that the content of <input /> will be updated in real time.

Let's talk about the handleGetInputValue method of onChange, which uses the target event attribute of the DOM Event object:

The target event property returns the target node of the event (the node that triggered the event), such as the element, document, or window that generated the event.

For more details, see the W3C standard introduction

Method 2: Use React's ref to access DOM elements and submit values

Stateless component writing:

const InputDemo = () => {
  let inputValue;
  const handlePost = (e) => {
    if (e) e.preventDefault();
    const valueTemp = inputValue.value;
    console.log(valueTemp, '------valueTemp');
    //Perform submission operations here, such as sending dispatch, etc.};
 
  return (
    <div>
      <form onSubmit={handlePost}>
        <input
          ref={input => inputValue = input}
        />
        <button onClick={handlePost}>Submit</button>
      </form>
    </div>
  )
};
 
export default InputDemo;

Stateful component writing:

import React from 'react';
 
class InputDemo extends React.Component {
  handlePost = (e) => {
    if (e) e.preventDefault();
    const valueTemp = this.inputValue.value;
    console.log(valueTemp, '------valueTemp');
    //Perform submission operations here, such as sending dispatch, etc.};
 
  render() {
    return (
      <div>
        <form onSubmit={this.handlePost}>
          <input
            ref={input => this.inputValue = input}
          />
          <button onClick={this.handlePost}>Submit</button>
        </form>
      </div>
    )
  }
};
 
export default InputDemo;

Ref is a handle provided by React to safely access a DOM element or a component instance. We can add a ref attribute to the element, and then accept the handle of the element in the DOM tree in the callback function, which will be returned as the first parameter of the callback function.

In addition to these two writing methods, you can also use Antd's Form component to implement form functions. Portal: React uses Antd's Form component to implement form functions

Summarize

This is the end of this article about 2 ways to get input values ​​and submit them in React. For more relevant content about getting input values ​​and submitting them in React, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use antd's form component in the react project to dynamically set the value of the input box
  • Solve the Can't resolve ''./locale'' problem in React after installing antd (recommended)
  • React implements dynamic switching of antd online themes
  • React configures the use of antd on-demand loading
  • Detailed explanation of adding css modules, sasss and antd using create-react-app
  • React uses antd's upload component to implement the file form submission function (complete code)

<<:  Detailed Introduction to Nginx Installation and Configuration Rules

>>:  5 Tips for Protecting Your MySQL Data Warehouse

Recommend

How to use custom images in Html to display checkboxes

If you need to use an image to implement the use ...

Javascript front-end optimization code

Table of contents Optimization of if judgment 1. ...

Explanation of the problem of selecting MySQL storage time type

The datetime type is usually used to store time i...

How to solve the problem of ERROR 2003 (HY000) when starting mysql

1. Problem Description When starting MYSQL, a pro...

Solution to the problem that Centos8 cannot install docker

Problem [root@zh ~]# [root@zh ~]# [root@zh ~]# yu...

WeChat applet to achieve the revolving lantern effect example

Preface In daily development, we often encounter ...

Installation and use of Apache stress testing tools

1. Download Go to the Apache official website htt...

Use scripts to package and upload Docker images with one click

The author has been working on a micro-frontend p...

WeChat applet implements the snake game

This article shares the specific code of the WeCh...

JavaScript example code to determine whether a file exists

1. Business Scenario I have been doing developmen...

Detailed explanation of nginx optimization in high concurrency scenarios

In daily operation and maintenance work, nginx se...

Solution to 1067 when Mysql starts in Windows

I just started working a few days ago and install...