[英]Why does my simple React form using hooks not work?
I'm learning the basics of React Hooks at the moment, I am wondering why this particular code does not work:我现在正在学习 React Hooks 的基础知识,我想知道为什么这个特定的代码不起作用:
function Form() {
const [input, setInput] = useState('');
let result = '';
function handleSubmit(e) {
e.preventDefault();
result = input;
}
return (
<React.Fragment>
<h1>Form practice</h1>
<form>
<input type="text" onChange={(e) => setInput(e.target.value)}></input>
<button type="submit" onClick={handleSubmit}>
submit
</button>
</form>
<h2>{result}</h2>
</React.Fragment>
);
}
I am simply expecting <h2>{result}</h2>
to display what is being captured in input
while the submit button is clicked.我只是希望
<h2>{result}</h2>
在单击提交按钮时显示input
中捕获的内容。 However, nothing happens.然而,什么也没有发生。 What is wrong with this logic?
这个逻辑有什么问题?
The way that a react component knows to rerender is that you set state. react 组件知道重新渲染的方式是设置 state。 Changing the value of a local variable will not cause a rerender.
更改局部变量的值不会导致重新渲染。 So if you want the
<input>
to change separately from the <h2>
, you will need to turn result
into a piece of state.因此,如果您希望
<input>
与<h2>
分开更改,则需要将result
转换为 state。
const [input, setInput] = useState('');
const [result, setResult] = useState('');
function handleSubmit(e) {
e.preventDefault();
setResult(input);
}
return (
<React.Fragment>
<h1>Form practice</h1>
<form>
<input type="text" onChange={(e) => setInput(e.target.value)}></input>
<button type="submit" onClick={handleSubmit}>
submit
</button>
</form>
<h2>{result}</h2>
</React.Fragment>
);
Simply because on each render of the component (whenever the state change, the component will render again) the code runs again and result
will set to value 0.仅仅是因为在组件的每次渲染中(每当 state 更改时,组件将再次渲染)代码再次运行并且
result
将设置为值 0。
Why not just render the input
instead of the result
variable?为什么不只渲染
input
而不是result
变量?
function Form() { const [input, setInput] = useState(''); function handleSubmit(e) { // do whatever you need to do to submit the form. } return ( <React.Fragment> <h1>Form practice</h1> <form> <input type="text" onChange={(e) => setInput(e.target.value)}></input> <button type="submit" onClick={handleSubmit}> submit </button> </form> <h2>{input}</h2> </React.Fragment> ); }
Hi ye need to set the result with useState as well so that re-render happens嗨,您还需要使用 useState 设置结果,以便重新渲染
function Form() {
const [input, setInput] = useState('');
const [result,setResult]= useState('');
const handleSubmit(e) {
e.preventDefault();
setResult(input);
}
return (
<React.Fragment>
<h1>Form practice</h1>
<form>
<input type="text" onChange={(e) => setInput(e.target.value)}></input>
<button type="submit" onClick={handleSubmit}>
submit
</button>
</form>
<h2>{result}</h2>
</React.Fragment>
);
}
now u will be able to see the changes现在您将能够看到更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.