问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/59204630/is-this-a-controlled-or-uncontrolled-react-component