如何使我的React / Bootstrap 4验证错误可见?

问题描述 投票:0回答:1

我正在使用React 16.13.0和Bootstrap4。我有一个React组件(src / components / Input.jsx),

import React from 'react';
import {FormControl, FormLabel} from 'react-bootstrap';

const Input = (props) => {
    return (
  <div className="form-group">
      <FormLabel>{props.title}</FormLabel>
      <FormControl
            type={props.type}
            id={props.name}
            name={props.name}
            value={props.value}
            placeholder={props.placeholder}
            onChange={props.handleChange}
          />

      {props.errors && props.errors[props.name] && (
          <FormControl.Feedback>
                 {props.errors[props.name].map((error, index) => ( 
                     <div key={`field-error-${props.name}-${index}`} className="fieldError">{error}</div>
                 ))} 
          </FormControl.Feedback>
      )}
  </div>
    )
}

导出默认输入;

如果他们是从表单提交返回的表单验证错误,我想在其中显示错误消息。

  async handleFormSubmit(e) {
    e.preventDefault();
    const NC = this.state.newCoop;
    delete NC.address.country;

    try {
      const response = await fetch('/coops/',{
        method: "POST",
        body: JSON.stringify(this.state.newCoop),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const result = await response.json();
        console.log('_result_: ', result);
        return result;
      }
      throw await response.json();
    } catch (errors) {
      console.log('_error_: ', errors);
      this.setState({ errors });
    }
  }

但是,当出现错误时,虽然我可以在HTML中看到存在带有错误消息的DIV,但它是不可见的。我想念什么?我猜bootstrap提供了一些使我的元素可见的标准方法。

reactjs validation bootstrap-4 visible
1个回答
0
投票

看起来您错误地设置了错误状态?在您的注释中,服务器返回"error: {phone: Array(1), web_site: Array(1)}",并且您正在设置状态,例如this.setState({ errors })。这样,您的error状态仍将是您的初始状态。

尝试使用this.setState({ errors: response.error })之类的东西>>

© www.soinside.com 2019 - 2024. All rights reserved.