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

How do I make my React/Bootstrap 4 validation error visible?

我正在使用 React 16.13.0 和 Bootstrap 4. 我有一个 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 提供了一些使我的元素可见的标准方法。

您似乎错误地设置了错误状态?在您的评论中,服务器 returns "error: {phone: Array(1), web_site: Array(1)}" 并且您正在设置这样的状态 this.setState({ errors })。这样,您的 error 状态仍将是您的初始状态。

试试 this.setState({ errors: response.error })

要获得可见的错误反馈,请为 FormControl 设置 isInvalid={Boolean(props.errors[props.name])},为 FormControl.Feedback 设置 type="invalid"

考虑解构 props 以简化您的代码。