SoFunction
Updated on 2025-04-07

Example of react method to get the value of the input input box

react various ways to get the value of the input input box

  • The first method: Uncontrolled component acquisition
  • The second method: controlled component acquisition

Uncontrolled component acquisition ref

import React , {Component} from 'react';
export default class App extends Component{
 search(){
 const inpVal = ;
 (inpVal);
 }
 
 render(){
 return(
  <div>
  <input type="text" ref={input =>  = input} defaultValue="Hello"/>
  <button onClick={(this)}></button>
  </div>
 )
 }
}

Use defaultValue to represent the default state of the component. At this time, it will only be rendered once, and subsequent renderings will not work; the input value will not change with external changes, but will change from its own state.

Controlled Components ({})

import React , {Component} from 'react';
export default class App extends Component{
 constructor(props){
 super(props);
  = {
  inpValu:''
 }
 }
 
 handelChange(e){
 ({
  inpValu:
 })
 }
 
 render(){
 return(
  <div>
  <input type="text" onChange={(this)} defaultValue={}/>
  </div>
 )
 }
}

The value of the input input box will change with the change of user input. OnChange gets the changed state through object e and updates the state. SetState triggers the rendering of the view according to the new state and completes the update.

This is the article about this example of the method of obtaining the value of the input input box in react. For more related contents of obtaining the value of the input input box in react, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!