onSubmit 在“react-material-ui-form-validator”中不起作用

问题描述

我在我的项目中使用了 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>

解决方法

我解决了这个问题。以前它没有返回任何 true or false 值,而是返回了 undefined。现在代码返回 truefalse

    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)
    );
  }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...