我react-material-ui-form-validator
在我的项目中使用。但是onSubmit
当我提交表单时没有触发。我尝试了很多但无法解决问题。我找不到为什么onSubmit
不工作。有人可以解释一下吗?
State
constructor(props) {
super(props);
this.form = React.createRef();
this.state = {
open: false,
currentColor: 'purple',
newName: '',
colors: [],
};
}
Validation Rule & handling events
componentDidMount() {
const { colors, currentColor } = this.state;
ValidatorForm.addValidationRule('isColorNameUnique', (value) => {
colors.every(({ name }) => name.toLowerCase() !== value.toLowerCase());
});
// eslint-disable-next-line no-unused-vars
ValidatorForm.addValidationRule('isColorUnique', (value) => {
colors.every(({ color }) => color !== currentColor);
});
}
addNewColor = (event) => {
event.preventDefault();
const { currentColor, colors, newName } = this.state;
const newColor = { color: currentColor, name: newName };
this.setState({ colors: [...colors, newColor], newName: '' });
};
handleChange = (evt) => {
this.setState({ newName: evt.target.value });
};
Validator Form
<ValidatorForm onSubmit={this.addNewColor} ref={this.form}>
<TextValidator
className={classes.textValidator}
value={newName}
placeholder="Color Name"
variant="filled"
margin="normal"
onChange={this.handleChange}
validators={['required', 'isColorNameUnique', 'isColorUnique']}
errorMessages={[
'this field is required',
'Color name must be Unique',
'Color already used',
]}
/>
<Button
className={classes.buttonCenter}
type="submit"
variant="contained"
color="primary"
style={{ backgroundColor: `${currentColor}` }}
>
Add Color
</Button>
</ValidatorForm>