我在我的项目中使用了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>发布于 2021-07-08 02:14:41
我修复了这个问题。以前,它不返回任何true or false值,而是返回undefined。现在代码返回true或false
componentDidMount() {
ValidatorForm.addValidationRule('isColorNameUnique', (value) =>
// eslint-disable-next-line react/destructuring-assignment
this.state.colors.every(({ name }) => name.toLowerCase() !== value.toLowerCase())
);
ValidatorForm.addValidationRule('isColorUnique', () =>
// eslint-disable-next-line react/destructuring-assignment
this.state.colors.every(({ color }) => color !== this.state.currentColor)
);
}https://stackoverflow.com/questions/68203709
复制相似问题