4

我第一次尝试使用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);

有人帮助我吗?

4

1 回答 1

5

专业提示:大多数支持良好的库在其 Github 存储库中都有一个示例目录。当我努力实现一个我以前没有使用过的库时,我只看一个示例

就像这个很棒的例子

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);
于 2019-12-06T14:10:27.950 回答