英文:
A question about react state change with input elements
问题
关于React的useState
,我有一个关于它如何处理输入元素状态更改的问题。
据我理解,我们可以使用useState来控制输入的值的方式大致如下:
const [state, setState] = useState("hello world");
return (
<input value={state} onChange={(e) => setState(e.target.value)} />
);
在这个示例中,输入的值与状态绑定在一起。
当输入的值发生变化时,它会触发一个状态变化,使用setState
函数重新渲染组件,并使用新的状态值来更新输入的值。
我的问题是:在状态值改变之前,输入的值如何改变?输入的值不是与状态的值绑定在一起吗?
英文:
I have a question about React's useState
, specifically on the way it handles state changes with input elements.
The way I understand it, the way we can control an input's value with useState goes something along this:
const [state,setState] = useState("hello world");
return (
<input value={state} onChange={(e) => setState(e.target.value)} />
);
In this example the value of the input is bound to state.
When the value of the input changes, it triggers a state change using setState
functions that in return re-renders the component with a new value for state, reflected in the value of the input.
My question is: How can the input's value change before the state's value changes? Doesn't the input's value bound to the state's value?
答案1
得分: 0
将onChange
更像是oninput
。
这来自React文档。
onChange
:事件处理函数。对于受控输入来说是必需的。在用户更改输入值时立即触发(例如,它在每次按键时触发)。表现类似于浏览器的输入事件。
这意味着用户正在输入会触发onChange
。在这里,您会设置状态,这会导致渲染,并允许您在屏幕上看到更新后的值。
英文:
Think of the onChange
more like an oninput
This is from the react docs.
>onChange: An Event handler function. Required for controlled inputs. Fires immediately when the input’s value is changed by the user (for example, it fires on every keystroke). Behaves like the browser input event.
This means that fact that the user is typing is causing the onChange
to fire. This is where you are then setting state, which causes a render and that allows you to see the updated value on screen.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论