如何将react-hook-form组成组件

时间:2019-12-06 14:03:42

标签: reactjs react-hook-form

我正在尝试第一次使用react-hook-formhttps://react-hook-form.com/)。 我不知道如何使用redux将它们组成为react组件。

import React from 'react'
import useForm from 'react-hook-form'

export default function SampleForm() {
    const { register, handleSubmit, watch, errors } = useForm()
    const onSubmit = data => { console.log(data) }

    console.log(watch('example')) // watch input value by passing the name of it

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input name="example" defaultValue="test" ref={register} />
            <input name="exampleRequired" ref={register({ required: true })} />
            {errors.exampleRequired && <span>This field is required</span>}
            <input type="submit" />
        </form>
    );
}
import React, { Component } from "react";
import { connect } from "react-redux";
import userForm from 'react-hook-form';
import SampleForm from "./SampleForm";

class Sample extends Component {
    constructor(props){
        super(props);
    }

    render() {
        return (
            <SampleForm />
        );
    }
}

export default connect()(Sample);

有人帮我吗?

1 个答案:

答案 0 :(得分:2)

专业提示:大多数受支持的库在其Github存储库中都有一个示例目录。在实现以前从未使用过的库时,我只看了examples之一。

像这个很棒的example

import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from "react-redux";
import useForm from 'react-hook-form';

function SampleForm() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => {
    alert(JSON.stringify(data));
  };

  return (
    <div className="App">
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label htmlFor="firstName">First Name</label>
          <input name="firstName" placeholder="bill" ref={register} />
        </div>

        <div>
          <label htmlFor="lastName">Last Name</label>
          <input name="lastName" placeholder="luo" ref={register} />
        </div>

        <div>
          <label htmlFor="email">Email</label>
          <input name="email" placeholder="bluebill1049@hotmail.com" type="email" ref={register} />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

class Sample extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <SampleForm />;
  }
}

export default connect()(Sample);

const rootElement = document.getElementById('root');
ReactDOM.render(<Sample />, rootElement);