如何让“react-bootstrap”和“react-hook-form”发挥良好作用?

Eri*_*ulz 10 reactjs react-bootstrap axios react-hook-form

我正在使用这两个很好的react表单库(连同axios):

  • react-bootstrap
  • react-hook-form(好像是react表单库在up上)

似乎没有明确的参考让两人打得很好?基本配方是什么?

这个问题这个问题 部分解决了这个问题,但它有点神秘。

(我试图在下面自己回答这个问题,但请随意改进 - 特别是如果它证明了这些库可以更好地协同工作)

Eri*_*ulz 9

这个例子看起来可行:

  1. 3 个字段和一个按钮
  2. 错误显示
  3. onSubmit 处理程序包括表单锁定和微调器

但这只是起点!

去做:

  • 使用react-hook-form进行客户端验证
  • 更漂亮的 React-Bootstrap 样式(但你拥有 React-Bootstrap 的全部功能,所以把自己搞砸了!)
import React from "react"                                                                            
import {Form, Button, Card, Container, Row, Col, } from 'react-bootstrap'                            
import Server from "../Server.js"                                                                    
import { JSONDisplayer } from "./Widgets"                                                            
import { useHistory } from "react-router-dom"                                                        
import { useForm, Controller } from 'react-hook-form'                                                
import {display_errors} from '../Utilities.js'                                                       
                                                                                                     
function Signup() {                                                                                  
                                                                                                     
  const history = useHistory()                                                                       
  const {setError, handleSubmit, control, reset, formState: {errors}, getValues                      
    } = useForm()                                                                                    
                                                                                                     
  const onSubmit = (data) => {                                                                       
    console.log('data', data)                                                                        
    return Server.post('/user/create/', data)                                                        
    .then(result => {                                                                                
      console.log('login result', result)                                                            
      history.push("/login")                                                                         
    })                                                                                               
    .catch(error => {display_errors(error, getValues, setError)})                                    
  }                                                                                                  
                                                                                                     
  return (                                                                                           
    <Container> <Row> <Col>                                                                          
    <Card><Card.Header>Create a new user</Card.Header><Card.Body>                                    
    <Form onSubmit={handleSubmit(onSubmit)} onReset={reset} >                                        
        <Form.Group className="mb-3" controlId="formUsername">                                       
          <Form.Label>User name</Form.Label>                                                         
            <Controller control={control} name="username"                                            
              defaultValue=""                                                                        
              render={({ field: { onChange, onBlur, value, ref } }) => (                             
                <Form.Control onChange={onChange} value={value} ref={ref}                            
                isInvalid={errors.username}                                                          
                placeholder="Enter user name" />)} />                                                
          <Form.Text className="text-muted">Login name</Form.Text>                                   
          <Form.Control.Feedback type="invalid">                                                     
            {errors.username?.message}                                                               
          </Form.Control.Feedback>                                                                   
        </Form.Group>                                                                                
                                                                                                     
        <Form.Group className="mb-3" controlId="formEmail">                                          
          <Form.Label>Email</Form.Label>                                                             
            <Controller control={control} name="email"                                               
              defaultValue=""                                                                        
              render={({field: {onChange, onBlur, value, ref}}) => (                                 
                <Form.Control onChange={onChange} value={value} ref={ref} type="email"               
                isInvalid={errors.email}                                                             
                placeholder="Enter email" />)} />                                                    
          <Form.Text className="text-muted">We need a valid email address.</Form.Text>               
          <Form.Control.Feedback type="invalid">                                                     
            {errors.email?.message}                                                                  
          </Form.Control.Feedback>                                                                   
        </Form.Group>                                                                                
                                                                                                     
        <Form.Group className="mb-3" controlId="password">                                           
          <Form.Label>Password</Form.Label>                                                          
            <Controller control={control} name="password"                                            
              defaultValue=""                                                                        
              render={({ field: { onChange, onBlur, value, ref } }) => (                             
                <Form.Control                                                                        
                onChange={onChange} value={value} ref={ref} type="password"                          
                isInvalid={errors.password}                                                          
                placeholder="Enter password" />                                                      
              )} />                                                                                  
          <Form.Text className="text-muted">Don't forget it!!</Form.Text>                            
          <Form.Control.Feedback type="invalid">                                                     
            {errors.password?.message}                                                               
          </Form.Control.Feedback>                                                                   
        </Form.Group>                                                                                
        <Controller control={control}                                                                
          render={({ field: { ref }, formState }) => (                                               
            <Button type="submit" disabled={formState.isSubmitting}                                  
               className="btn btn-primary">                                                          
               {formState.isSubmitting && <span className="spinner-border spinner-border-sm mr-1" />}
               Save                                                                                  
            </Button>                                                                                
          )} />                                                                                      
    </Form></Card.Body></Card>                                                                       
    </Col> </Row> </Container>                                                                       
    )                                                                                                
                                                                                                     
}                                                                                                    
                                                                                                     
export default Signup                                                                                
Run Code Online (Sandbox Code Playgroud)

通用axios->react-hook-form错误转录器函数:

// transcibe axios errors to react-hook-form
function display_errors(error, getValues, setError) {
  const errs = error.response.data || []
  var got_a_useful_message = false
  // loop over all the fields and set error:  
  for (var field of Object.keys(getValues())) {
    if (errs[field]) {
      got_a_useful_message = true
      setError(field, {
        type: "server",        
        message: errs[field].join(' | ')})
    }
  }
  if (!got_a_useful_message) {
    alert('something has gone wrong')
  }
}

export {display_errors}


Run Code Online (Sandbox Code Playgroud)