0

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>
4

1 回答 1

0

我解决了这个问题。以前它没有返回任何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)
    );
  }
于 2021-07-07T18:14:40.683 回答