如何在 react-bootstrap 中使用验证状态

How to use validate-state with react-bootstrap

我正在使用 react-bootstrap 并尝试使用 validate-state 选项验证表单。当我提交一个会使输入字段变为红色的表单时,我不知道如何使用 getValidationState()return error。当前,当加载表单时,我在控制台 ProfileCandidateForm.getValidationState ReferenceError: error is not defined.

中收到一条错误消息

如果我删除 getValidationState() 我可以提交表单,如果它出错 returns 则将错误发送到警告框。我想将其更改为 bootstrap 中的 validate-state

感谢任何帮助。仍然围绕着 React。

export default class ProfileCandidateForm extends Component {
  constructor(props) {
    super(props);

    var profileCandidate = this.props.profileCandidate;
    var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;


    this.state = {
      firstName: firstName || "",
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();
    var profileCandidate = this.state;

    insertProfileCandidate.call({profileCandidate}, (error) => {
      if (error) {
        alert(error.reason);
      }
    });
  }

  getValidationState() {
    if (error) return 'error';
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit.bind(this)}>
        <FormGroup
          validationState={this.getValidationState()}
          >
            <FormControl
              type="text"
              name="firstName"
              value={this.state.firstName}
              placeholder="First name"
              onChange={this.handleChange}
            />
            <FormControl.Feedback />
          </FormGroup>
          <FormGroup >
            <Button type="submit">
              Save
            </Button>
          </FormGroup>
        </form>
      )
    }
  }

  ProfileCandidateForm.propTypes = {
    profileCandidate: PropTypes.object.isRequired,
  }

您需要在getValidationState() 函数中引用文本字段的值(状态)。然后 return null(无可见验证),'success'(绿色可见验证),或 'error'(红色验证)。

这是我的 getValidationState 函数之一。

getValidationState() {
    var value = this.state.value;

    if (value===null || value==='') { return null; }

    var valid = this._getValidity(value)
    if (valid===true) {
      return 'success';
    } else {
      return 'error';
    }
}