What is the method for dynamically getting and setting input values in React?

In React, you can use useState to achieve dynamic input value changes.

First, we need to import useState.

import React, { useState } from 'react';

Next, define a state variable and corresponding update function within the component.

const [inputValue, setInputValue] = useState('');

Next, bind the value of the input box to a state variable and update the value of the state variable through the update function.

<input
  type="text"
  value={inputValue}
  onChange={e => setInputValue(e.target.value)}
/>

By setting value={inputValue}, the value of the state variable can be bound to the input box. When the value of the input box changes, the onChange event will be triggered and the state variable’s value will be updated through the update function setInputValue.

Finally, you can use inputValue to retrieve the value of the input box and process it accordingly.

The complete sample code is as follows:

import React, { useState } from 'react';

const App = () => {
  const [inputValue, setInputValue] = useState('');

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={e => setInputValue(e.target.value)}
      />
      <p>输入的值是:{inputValue}</p>
    </div>
  );
}

export default App;

In the example above, the value in the input box will be displayed in real time in the

tag below.

bannerAds