原文地址:Controlled and uncontrolled form inputs in React don’t have to be complicated
react的form受控和非受控话题
You may have seen many articles saying **“you shouldn’t use setState
,”**and the docs are claiming “ref
s are bad”… That is so contradictory. It’s hard to understand how to “get it right” and even what are the criteria for choosing.
(译:你可能已经看过很多文章说:“你不应该去使用 setState 去实现表单输入(setState是受控)”,并且官方文档声称:“使用 ref 的方式实现表单输入是不好的(ref是非受控)”。这些是互相矛盾的。这是很难去理解的,怎么样才能“得到正确的答案”,或者说选择标准是什么?)
How the hell are you supposed to make forms? (翻译:你到底应该怎么去实现form表单?)
After all, forms are central to many web apps out there. And yet, form handling in React seems to be a bit of a… corner stone?(翻译:毕竟,表单是许多网络应用程序的核心。然而,React中的表单处理似乎有点像一个墙角石)
Fear no more. Let me show you the differences between the approaches, as well as when you should use each.(翻译:不要担心,让我向你展示这些方法之间的差异,以及何时应该使用哪一种方法。)
The Uncontrolled(非受控)
Uncontrolled inputs are like traditional HTML form inputs:(翻译:非受控就像传统的HTML表单输入,如下:)
class Form extends Component {
render() {
return (
<div>
<input type="text" />
</div>
);
}
}
They remember what you typed. You can then get their value using a ref. For example, in onClick
handler of a button:&