There may be other ways to do this that I do not know about.
But I prefer to do change processing in a generic method for a certain type of generic fields, such as <input type of text />
This is an example input field -
<input
onChange = {this.onChange}
value = {this.state.firstName}
type = "text"
name = {"firstName"}
/>
I save the name of the status field and the name "name" . After that I write a general change handler for all such fields.
You need to write only one line in the change handler.
onChange(e) {
this.setState({[e.target.name]: e.target.value});
}
I am using es6 dynamic property parameter from string as property name
{ ["propName] : propValue }.
, -
.
_bind(...methods) {
methods.forEach( (method) => this[method] = this[method].bind(this) );
}
_bind .
constructor(props){
super(props);
this.state = {
regName : '',
regAdd1 : '',
regAdd2 : '',
regState : '',
regZipCode : '',
regCity : '',
regPhone : ''
};
// add bindings .... ugh..
//this.changeRegAdd1 = this.changeRegAdd1.bind(this);
//this.changeRegAdd2 = this.changeRegAdd2.bind(this);
//Similary binding for other handlers...
this._bind(
'changeRegName',
'changeReg1' , 'changeRegAdd2'
// and so on.
);
}
EDIT:
-
- , , .
- - , .
, , . .
validateInput() {
let errors = {};
Object.keys(this.state)
.forEach((stateKey) => {
isEmpty(this.state[stateKey]) ? (errors[stateKey] = `*required` ) : null;
});
return {
errors,
isValid : isEmptyObj(errors)
};
}
isFormValid() {
const { errors, isValid } = this.validateInput();
if (!isValid) {
this.setState({ errors});
}
return isValid;
}
onSubmit(e) {
e.preventDefault();
this.setState({errors : {}});
if (this.isFormValid()) {
}
}
calld isEmpty, isEmptyObj. , undefined, .
, .