gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:01:55 25 4
gpt4 key购买 nike

我正在尝试使用 react-hook-form ( https://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);

有人帮我吗?

最佳答案

专业提示:大多数支持良好的库在其 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);

关于reactjs - 如何将 react-hook-form 组合成组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com