简体   繁体   English

this.refs vs value in react for form use

[英]this.refs vs value in react for form usage

How would you guys do a form submission? 你们将如何提交表单? I have no problem making a form but I saw 2 different approach. 我制作表格没有问题,但是我看到了两种不同的方法。 Personally I use state to bind the form value 我个人使用状态来绑定表单值

<input onChange={this.handleInputChange} value={this.state.username} type="text" name="username" />

to get the input value I will do this 获取输入值,我将这样做

handleInputChange = () => (
   const username = e.target.username.value;
)

It worked but not sure this is a good approach, another approach is using refs. 它起作用了,但不确定这是一个好方法,另一种方法是使用引用。

The good thing is no need to put onChange on every fields, in onSubmit simply do this 好处是无需在每个字段上放置onChange,只需在onSubmit中执行此操作

this.refs.username.value

and you have ur element like this <input ref="username" type="text" /> 并且您有这样的ur元素<input ref="username" type="text" />

But how to set the value of the username if the initial load is an ajax? 但是,如果初始加载为ajax,如何设置用户名的值?

I recommend to not use refs unless you have no other way of doing things. 我建议不要使用引用,除非您没有其他处理方法。 https://facebook.github.io/react/docs/refs-and-the-dom.html https://facebook.github.io/react/docs/refs-and-the-dom.html

Your approach with binding the value to state seems like the way to go. 您将值绑定到状态的方法似乎很可行。

The good thing about using the onChange(one-way binding) is that you have full control over the input data. 使用onChange(单向绑定)的好处是,您可以完全控制输入数据。

Say if you want input to have only alphabets 假设您只想输入字母

handleInputChange = () => (
   // you can have validation code here to check if the 
   // input has only alphabets and return if otherwise 
   const username = e.target.username.value;
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM