这是受控制还是不受控制的React组件? [英] Is this a controlled or uncontrolled React component?

查看:63
本文介绍了这是受控制还是不受控制的React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有关此问题的答案,但没有一个与我的设置类似:

什么是受控组件和非受控组件?

我有一个父级组件和多个子级作为输入.每个输入都有一个defaultValue,该值是使用从父级接收到的prop设置的,输入的验证是在onBlur上执行的.这是因为验证是异步的,所以onChange会像疯狂一样放慢应用程序的速度.

该业务流程如何命名?传统的受控"定义似乎是在每个onChange上更新的输入,而非受控"输入是管理其自身内部状态的输入,该内部状态随后可通过ref访问.我的设置似乎没有做到这两者,都坐在中间的某个地方-还是没有?

更新:这是一个 CodeSandbox .

解决方案

如果我正确理解您的设置,则您的输入将不受控制,因为它们的状态保存在DOM中,而不是React状态. Validation 是一个单独的问题,可以同步或异步发生.您可以使React状态保留您为验证所做的任何事情的值.请注意,大多数时候您都不想阻止输入甚至包含无效值-您只想确保在值无效时用户不能提交表单.因此,您可以使用onChange处理程序来设置状态的某些值,如下所示:

<input type="text" 
  value={this.state.myValue} 
  onChange={val => this.setState({myValue: val}, 
    ()=> this validateMyValue(this.state.myValue))}} />

this.validateMyValue可以是异步的,并且在验证失败时可以执行所需的任何操作.那将是一个受控组件,可以执行您想要的操作.

I read the answers on this question but none is similar to my set up:

What are controlled components and uncontrolled components?

I have a parent component and many children as inputs. Each input has a defaultValue that is set using a prop received from the parent and the validation of the input is performed on onBlur. This is because the validation is asynchronous, so onChange would slow down the app like crazy.

How is this orchestration called? The traditional definition for "controlled" seems to be an input which updates on every onChange, while an "uncontrolled" input is one which manages its own internal state, which is later accessed via a ref. My set up seems to fall short of both, sitting somewhere in the middle - or not?

Update: Here's a CodeSandbox.

解决方案

If I understand your setup correctly, your inputs are uncontrolled, because their state is held in the DOM rather than in React state. Validation is a separate concern, which can happen synchronously or asynchronously. You can let React state hold the values whatever you do for validation. Note that most of the time you don't want to prevent the input from even having an invalid value - you just want to ensure that the user can't submit the form while the values are invalid. Thus you can have an onChange handler to set some value on state as in the following:

<input type="text" 
  value={this.state.myValue} 
  onChange={val => this.setState({myValue: val}, 
    ()=> this validateMyValue(this.state.myValue))}} />

this.validateMyValue could be asynchronous, and do whatever is required if validation fails. That would be a controlled component doing what you want.

这篇关于这是受控制还是不受控制的React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆