所以,我有一个带有多个输入的表单,这些输入在onChange
时更新状态。
我的目的是,让用户更改值时更新表单的state
以保存这些更改。以下是使用ES6类的代码:
super(props);
this.state = {
post: this.props.content // this is an object {title: '', description: ''}
}
// I have all the methods below this.method = this.method.bind(this) up here.
}
handleTitle(title) { // gets title from input onChange event
let post = update(this.state.post, {title: {$set: title}}); // using import update from 'immutability-helper' for changing object
this.setState({ post });
this.checkPostApproval();
} // this all works, post is updated. I have the same code for description.
checkPostApproval() {
// here I want to check the post values and make sure they are valid.
// and either allow or deny submission.
if (this.state.post['title'] && this.state.post['description']) {
this.setState({isApproved: true});
} else {
this.setState({isApproved: false});
}
}
问题:
当用户设置标题和描述后,isApproved会变为true(我想要的)。 但是,如果用户将标题更改为“” ,则批准仍然保持为true(不是我想要的)。 如果用户开始键入描述,那么批准开关将切换到false。 我认为这与组件生命周期以及状态何时被设置有关,但我不确定。
我不介意使用jQuery来检查验证,但我希望只需在输入更改后检查值,然后使用方法和props更新邮政编码。
在各个输入字段中使用
onChange
事件处理程序更新状态对象并进行验证的最佳实践方法是什么?最终,如果存在任何无效输入,则
isApproved
应为false。