如何将焦点移到reactjs中的错误字段

时间:2019-03-04 22:43:52

标签: reactjs redux react-redux semantic-ui

我正在使用语义UI反应 https://react.semantic-ui.com/collections/form/#shorthand-subcomponent-id 在我的示例中,表单有两个字段。我还完成了必需的验证。当我单击button时,如果字段为空,则显示red border到字段。我希望焦点将移至第一个错误字段字段中有错误 这是我的代码 https://codesandbox.io/s/8yyqvvvj18

validateForm = () => {
    const { subscriberFirstName, subscriberMiddleName } = this.state,
      obj = { ...this.state };
    /* Empty validation*/
    let formError = false;
    if (!subscriberFirstName) {
      obj.subscriberFirstNameError = true;
      obj.formErrorMessage = "mandatory";
      formError = true;
    } else {
      obj.subscriberFirstNameError = false;
    }
    if (!subscriberMiddleName) {
      obj.subscriberMiddleNameError = true;
      obj.formErrorMessage = "mandatory";
      formError = true;
    } else {
      obj.subscriberMiddleNameError = false;
    }

    if (formError) {
      this.setState(preState => ({
        ...preState,
        ...obj,
        formError: true
      }));
    } else {
      this.setState(
        preState => ({
          ...preState,
          ...obj,
          formError: false,
          formErrorMessage: ""
        }),
        () => {
          //  this.saveForm(false);
        }
      );
    }
  };

当用户单击按钮时,我希望焦点将移至第一个错误字段。

如果表单焦点出现错误,则会移至第一个错误字段

0 个答案:

没有答案