P粉4690907532023-09-01 14:07:48
In React.js, using methods such as querySelector to directly manipulate the DOM and set the value of an input element may not reflect the expected changes in the DOM. This is because React has its own virtual DOM (VDOM) which it can use to efficiently update the real DOM.
React encourages you to manage the state of your components and let React handle updates to the DOM for you, rather than manipulating the DOM directly. Here's how to achieve the desired behavior in React:
Use the useState hook to declare a state variable:
import React, { useState } from 'react'; function MyComponent() { const [inputValue, setInputValue] = useState(''); // ... }
When you want to change the value of the input box, update the inputValue state variable:
setInputValue("blablablabla");
Use the inputValue state variable to render the input element:
<input type="text" value={inputValue} onChange={e => setInputValue(e.target.value)} />
With this approach, React will manage the state of the input elements and automatically update the DOM when the state changes.