我正在提交一个返回一系列错误的表单,但我无法弄清楚如何让每个单独的错误出现在正确的输入字段下。现在,所有错误都会打印在每个输入字段下。我在用着react-bootstrap
。任何帮助,将不胜感激。
getValidationState() {
var errors = this.state.errors;
if (!$.isEmptyObject(errors))
{
errors.forEach(function(error) {
console.log("error:", error.name);
});
}
}
render() {
const inputProps = {
value: this.state.address,
onChange: this.onChange,
}
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<FormGroup
validationState={this.getValidationState()} >
<FormControl
type="text"
name="firstName"
value={this.state.firstName}
placeholder="First name"
onChange={this.handleChange}
/>
<FormControl.Feedback />
{this.state.errors && this.state.errors.length &&
<HelpBlock>
{this.state.errors.map((error, i) => <p key={i}>HEllo{error.value}</p>)}
</HelpBlock>
}
</FormGroup>
<FormGroup >
<FormControl
type="text"
name="lastName"
value={this.state.lastName}
placeholder="Last name"
onChange={this.handleChange}
/>
{this.state.errors && this.state.errors.length &&
<HelpBlock>
{this.state.errors.map((error, i) => <p key={i}>HEllo{error.value}</p>)}
</HelpBlock>
}
</FormGroup>
<FormGroup >
<Button type="submit">
Save
</Button>
</FormGroup>
</form>
)
}
每个输入的错误消息应单独存储和显示(也通过使用状态):
constructor(props){
super(props)
this.state = {
firstNameErr: '',
lastNameErr: '',
}
this.getValidationState = this.getValidationState.bind(this);
}
getValidationState() {
var errors = this.state.errors;
if (!$.isEmptyObject(errors))
{
var firstErr = '';
var lastErr = '';
errors.forEach((error) => {
console.log("error:", error.name);
// Check each error to see which input it belongs to
// NOTE: please also consider using error.name instead, if error.message is invalid, thanks!
if(error.message.indexOf('firstName') != -1){
firstErr = error.message;
}
if(error.message.indexOf('lastName') != -1){
lastErr = error.message
}
});
this.setState({
firstNameErr: firstErr,
lastNameErr: lastErr,
});
}
}
render() {
const inputProps = {
value: this.state.address,
onChange: this.onChange,
}
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<FormGroup
validationState={this.getValidationState()} >
<FormControl
type="text"
name="firstName"
value={this.state.firstName}
placeholder="First name"
onChange={this.handleChange}
/>
<FormControl.Feedback />
<HelpBlock>
<p className="text-danger">{this.state.firstNameErr}</p>
</HelpBlock>
</FormGroup>
<FormGroup >
<FormControl
type="text"
name="lastName"
value={this.state.lastName}
placeholder="Last name"
onChange={this.handleChange}
/>
<HelpBlock>
<p className="text-danger">{this.state.lastNameErr}</p>
</HelpBlock>
</FormGroup>
<FormGroup >
<Button type="submit">
Save
</Button>
</FormGroup>
</form>
)
}
这就是想法,如果它还不起作用,请向我显示您控制台中的一些错误,谢谢
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)