【发布时间】:2018-12-04 08:22:08
【问题描述】:
我正在使用“react-native-material-textfield”,它运行良好,但是在单击提交按钮时我需要显示空字段的错误。我已经搜索了很多但没有找到任何解决方案。
【问题讨论】:
标签: validation react-native textfield
我正在使用“react-native-material-textfield”,它运行良好,但是在单击提交按钮时我需要显示空字段的错误。我已经搜索了很多但没有找到任何解决方案。
【问题讨论】:
标签: validation react-native textfield
如果您的验证过程失败,请在您的状态中输入错误消息并在单击提交按钮后填写一条消息。
render(){
return (
<View>
<TextField
{...props}
error={this.state.error}
errorColor={'red'}
onFocus={() => this.setState({error: ''})}
/>
<Button {...props} />
</View>)}
检查开发者 github 存储库上的 example。
【讨论】:
根据模块文档和示例,只要每个字段的 this.state.errors 不为空,就会显示其错误。所以你的表单应该是这样的:
class Form extends Component {
// ... Some required methods
onSubmit() {
let errors = {};
['firstname'] // This array should be filled with your fields names.
.forEach((name) => {
let value = this[name].value();
if (!value) {
errors[name] = 'Should not be empty'; // The error message when field is empty
}
});
this.setState({ errors });
}
render() {
let { errors = {}, data } = this.state;
return (
<View>
<TextField
value={data.firstname}
onChangeText={this.onChangeText}
error={errors.firstname}
/>
<Text onPress={this.onSubmit}>Submit</Text>
</View>
);
}
}
【讨论】: