在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
React Hook Form 是一个强大而高效的库,用于在 React 应用程序中管理表单值。 它利用 React 钩子提供无缝、高性能的体验,无需任何控制器组件。 在本文中,我们将探讨使用自定义错误信息提交 React Hook 表单的基础知识及其优势,并提供代码示例帮助您入门。
性能:React Hook Form 使用不受控制的组件和本地 HTML 输入,减少了重新呈现的次数,提高了性能。
简单:应用程序接口(API)直观易用,所需的代码行数少于其他表单库。
要安装 React Hook Form,请运行以下命令:
npm install react-hook-form
or
yarn add react-hook-form
npm install react-hook-form
or
yarn add react-hook-form
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install react-hook-form @or yarn add react-hook-form
让我们使用 React Hook Form 创建一个没有受控组件和子组件的简单注册表单。
import { useForm } from "react-hook-form";
import { useForm } from "react-hook-form";
import
If True Then
useForm
End If
from "react-hook-form"
const { register, handleSubmit, formState: { errors } } = useForm();
const { register, handleSubmit, formState: { errors } } = useForm();
'INSTANT VB TODO TASK: The following line could not be converted:
const
'INSTANT VB TODO TASK: The following line could not be converted:
register, handleSubmit, formState:
If True Then
errors
End If
} = useForm()
function RegistrationForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>First Name</label>
{errors.firstName && <span>This field is required</span>}
</div>
<div>
<label>Last Name</label>
{errors.lastName && <span>This field is required</span>}
</div>
<div>
<label>Email</label>
{errors.email && <span>Invalid email address</span>}
</div>
</form>
);
}
function RegistrationForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>First Name</label>
{errors.firstName && <span>This field is required</span>}
</div>
<div>
<label>Last Name</label>
{errors.lastName && <span>This field is required</span>}
</div>
<div>
<label>Email</label>
{errors.email && <span>Invalid email address</span>}
</div>
</form>
);
}
Private Function RegistrationForm() As [function]
'INSTANT VB TODO TASK: The following line could not be converted:
const
If True Then
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' register, handleSubmit, formState:
' {
' errors
' }
} = useForm()
const onSubmit = Sub(data)
console.log(data)
End Sub
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: return (<form onSubmit={handleSubmit(onSubmit)}> <div> <label> First Name</label> {errors.firstName && <span> This field is required</span>} </div> <div> <label> Last Name</label> {errors.lastName && <span> This field is required</span>} </div> <div> <label> Email</label> {errors.email && <span> Invalid email address</span>} </div> </form>);
Return (<form onSubmit={handleSubmit(onSubmit)}> (Of div) (Of label) First Name</label> {errors.firstName AndAlso (Of span) This TypeOf field Is required</span>} </div> (Of div) (Of label) Last Name</label> {errors.lastName AndAlso (Of span) This TypeOf field Is required</span>} </div> (Of div) (Of label) Email</label> {errors.email AndAlso (Of span) Invalid email address</span>} </div> </form>)
End If
React Hook Form 支持更高级的用例,例如与第三方 UI 库集成和自定义验证。
import { TextField, Button } from '@material-ui/core';
import { useForm, Controller } from 'react-hook-form';
function MaterialUIForm() {
const { control, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="firstName"
control={control}
defaultValue=""
render={({ field }) => <TextField {...field} label="First Name" />}
/>
<Controller
name="lastName"
control={control}
defaultValue=""
render={({ field }) => <TextField {...field} label="Last Name" />}
/>
<Button type="submit">Submit</Button>
</form>
);
}
import { TextField, Button } from '@material-ui/core';
import { useForm, Controller } from 'react-hook-form';
function MaterialUIForm() {
const { control, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="firstName"
control={control}
defaultValue=""
render={({ field }) => <TextField {...field} label="First Name" />}
/>
<Controller
name="lastName"
control={control}
defaultValue=""
render={({ field }) => <TextField {...field} label="Last Name" />}
/>
<Button type="submit">Submit</Button>
</form>
);
}
import
If True Then
TextField, Button
End If
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'from '@material-ui/core'; import { useForm, Controller } from 'react-hook-form'; @function MaterialUIForm() { const { control, handleSubmit } = useForm(); const onSubmit = (data) => { console.log(data); }; Return(<form onSubmit={handleSubmit(onSubmit)}> <Controller name="firstName" control={control} defaultValue="" render={({ field }) => <TextField {...field} label="First Name" />} /> <Controller name="lastName" control={control} defaultValue="" render={({ field }) => <TextField {...field} label="Last Name" />} /> <Button type="submit"> Submit</Button> </form>); }
产量
function CustomValidationForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>Username</label>
<input {...register("username", {
required: "Username is required",
validate: value => value !== "admin"
"Username cannot be 'admin'"
})} />
{errors.username && <span>{errors.username.message}</span>}
</div>
</form>
);
}
function CustomValidationForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>Username</label>
<input {...register("username", {
required: "Username is required",
validate: value => value !== "admin"
"Username cannot be 'admin'"
})} />
{errors.username && <span>{errors.username.message}</span>}
</div>
</form>
);
}
Private Function CustomValidationForm() As [function]
'INSTANT VB TODO TASK: The following line could not be converted:
const
If True Then
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' register, handleSubmit, formState:
' {
' errors
' }
} = useForm()
const onSubmit = Sub(data)
console.log(data)
End Sub
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
Return (<form onSubmit={handleSubmit(onSubmit)}> (Of div) (Of label) Username</label> <input {...register("username", { required:= "Username is required", validate:= Function(value) value <>= "admin" "Username cannot be 'admin'" })} /> {errors.username AndAlso (Of span){errors.username.message}</span>} </div> </form>)
End If
IronPDF是一个流行的 PDF 文档生成库,用于生成、编辑和转换 PDF。 IronPDF 软件包专为 Node.js 应用程序设计。 以下是 IronPDF NPM 软件包的一些主要功能和详细信息。
直接从 URL 生成 PDF 文档,允许您捕捉网页内容并以编程方式将其保存为 PDF 文件。
将 HTML 内容轻松转换为 PDF 文档。 此功能特别适用于从网页内容生成动态PDF。
轻松合并、拆分和操作现有的PDF文档。 IronPdf 提供附加页面、分割文档等功能。
通过设置密码或应用数字签名来保护您的PDF文档。 IronPDF 提供选项以保护您的敏感文档免受未经授权的访问。
生成高质量的PDF文档,精确渲染文本、图像和格式。 IronPDF 确保您生成的 PDF 保持与原始内容的一致性。
IronPDF兼容多个平台,包括Windows、Linux和macOS,使其适用于广泛的开发环境。
使用其npm软件包轻松将IronPDF集成到您的Node.js应用程序中。 API 文档详实,使将 PDF 生成功能集成到您的项目中变得简单明了。
要安装 IronPDF NPM 软件包,请使用以下命令:
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
IRON VB CONVERTER ERROR developers@ironsoftware.com
安装依赖项:首先,创建一个新的 Next.js 项目(如果你还没有)使用以下命令。 请参考Next.js 设置页面
npx create-next-app@latest reacthookform-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest reacthookform-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npx create-@next-app@latest reacthookform-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
接下来,导航到你的项目目录:
cd reacthookform-pdf
cd reacthookform-pdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'cd reacthookform-pdf
安装所需的软件包:
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add -D prettier
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add -D prettier
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 yarn add -D prettier
现在,让我们创建一个使用 IronPDF 生成 PDF 的简单示例。
PDF 生成 API:第一步是创建生成 PDF 文档的后台 API。 由于IronPDF只在服务器端运行,我们需要创建一个API,以便在用户想生成PDF时调用。 在 pages/api/pdf.js 路径下创建一个文件,并添加以下内容。
IronPDF需要许可证密钥,您可以从许可证页面Please provide the content you would like translated into Chinese along with the code where it should be placed.
// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "your license";
export default async function handler(req, res) {
try {
const f = req.query.f;
const l = req.query.l;
const e = req.query.e;
let content = "<h1>Demo React Hook Form and Generate PDF Using IronPDF</h1>"
content+="<p>First Name:"+f+"</p>";
content+="<p>Last Name:"+l+"</p>";
content+="<p>Email:"+e+"</p>";
const pdf = await PdfDocument.fromHtml(content);
const data = await pdf.saveAsBuffer();
console.error("data PDF:", data);
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
"attachment; filename=awesomeIron.pdf",
);
res.send(data);
} catch (error) {
console.error("Error generating PDF:", error);
res.status(500).end();
}
}
// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "your license";
export default async function handler(req, res) {
try {
const f = req.query.f;
const l = req.query.l;
const e = req.query.e;
let content = "<h1>Demo React Hook Form and Generate PDF Using IronPDF</h1>"
content+="<p>First Name:"+f+"</p>";
content+="<p>Last Name:"+l+"</p>";
content+="<p>Email:"+e+"</p>";
const pdf = await PdfDocument.fromHtml(content);
const data = await pdf.saveAsBuffer();
console.error("data PDF:", data);
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
"attachment; filename=awesomeIron.pdf",
);
res.send(data);
} catch (error) {
console.error("Error generating PDF:", error);
res.status(500).end();
}
}
' pages/api/pdf.js
import
If True Then
IronPdfGlobalConfig, PdfDocument
End If
from "@ironsoftware/ironpdf"
' Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "your license"
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'export default async @function handler(req, res)
'{
' try
' {
' const f = req.query.f;
' const l = req.query.l;
' const e = req.query.e;
' let content = "<h1>Demo React Hook Form and Generate PDF Using IronPDF</h1>" content+="<p>First Name:"+f+"</p>";
' content+="<p>Last Name:"+l+"</p>";
' content+="<p>Email:"+e+"</p>";
' const pdf = await PdfDocument.fromHtml(content);
' const data = await pdf.saveAsBuffer();
' console.@error("data PDF:", data);
' res.setHeader("Content-Type", "application/pdf");
' res.setHeader("Content-Disposition", "attachment; filename=awesomeIron.pdf",);
' res.send(data);
' }
' catch (@error)
' {
' console.@error("Error generating PDF:", @error);
' res.status(500).@end();
' }
'}
现在修改 index.js。
import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
export default function Home() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
generatePdf(data);
};
const generatePdf = async (data) => {
try {
console.log("/api/pdf?f=" + data["firstName"]+"&l="+data["lastName"]+"&e="+data["email"]);
const response = await fetch("/api/pdf-html?f=" + data["firstName"]+"&l="+data["lastName"]+"&e="+data["email"]);
const blob = await response.blob();
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "awesomeIron.pdf");
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} catch (error) {
console.error("Error generating PDF:", error);
}
};
const handleChange = (event) => {
setText(event.target.value);
};
return (
<div className={styles.container}>
<Head>
<title>Generate PDF Using IronPDF</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1>Demo React Hook Form and Generate PDF Using IronPDF</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>First Name</label>
{errors.firstName && <span>This field is required</span>}
</div>
<div>
<label>Last Name</label>
{errors.lastName && <span>This field is required</span>}
</div>
<div>
<label>Email</label>
{errors.email && <span>Invalid email address</span>}
</div>
<button type="submit" >Submit and Generate PDF</button>
</form>
</main>
<style jsx>{`
main {
padding: 5rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
footer {
width: 100%;
height: 100px;
border-top: 1px solid #eaeaea;
display: flex;
justify-content: center;
align-items: center;
}
footer img {
margin-left: 0.5rem;
}
footer a {
display: flex;
justify-content: center;
align-items: center;
text-decoration: none;
color: inherit;
}
code {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
font-size: 1.1rem;
font-family:
Menlo,
Monaco,
Lucida Console,
Liberation Mono,
DejaVu Sans Mono,
Bitstream Vera Sans Mono,
Courier New,
monospace;
}
`}</style>
<style jsx global>{`
html,
body {
padding: 0;
margin: 0;
font-family:
-apple-system,
BlinkMacSystemFont,
Segoe UI,
Roboto,
Oxygen,
Ubuntu,
Cantarell,
Fira Sans,
Droid Sans,
Helvetica Neue,
sans-serif;
}
* {
box-sizing: border-box;
}
`}</style>
</div>
);
}
import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
export default function Home() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
generatePdf(data);
};
const generatePdf = async (data) => {
try {
console.log("/api/pdf?f=" + data["firstName"]+"&l="+data["lastName"]+"&e="+data["email"]);
const response = await fetch("/api/pdf-html?f=" + data["firstName"]+"&l="+data["lastName"]+"&e="+data["email"]);
const blob = await response.blob();
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "awesomeIron.pdf");
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} catch (error) {
console.error("Error generating PDF:", error);
}
};
const handleChange = (event) => {
setText(event.target.value);
};
return (
<div className={styles.container}>
<Head>
<title>Generate PDF Using IronPDF</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1>Demo React Hook Form and Generate PDF Using IronPDF</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>First Name</label>
{errors.firstName && <span>This field is required</span>}
</div>
<div>
<label>Last Name</label>
{errors.lastName && <span>This field is required</span>}
</div>
<div>
<label>Email</label>
{errors.email && <span>Invalid email address</span>}
</div>
<button type="submit" >Submit and Generate PDF</button>
</form>
</main>
<style jsx>{`
main {
padding: 5rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
footer {
width: 100%;
height: 100px;
border-top: 1px solid #eaeaea;
display: flex;
justify-content: center;
align-items: center;
}
footer img {
margin-left: 0.5rem;
}
footer a {
display: flex;
justify-content: center;
align-items: center;
text-decoration: none;
color: inherit;
}
code {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
font-size: 1.1rem;
font-family:
Menlo,
Monaco,
Lucida Console,
Liberation Mono,
DejaVu Sans Mono,
Bitstream Vera Sans Mono,
Courier New,
monospace;
}
`}</style>
<style jsx global>{`
html,
body {
padding: 0;
margin: 0;
font-family:
-apple-system,
BlinkMacSystemFont,
Segoe UI,
Roboto,
Oxygen,
Ubuntu,
Cantarell,
Fira Sans,
Droid Sans,
Helvetica Neue,
sans-serif;
}
* {
box-sizing: border-box;
}
`}</style>
</div>
);
}
Private Head As import
Private styles As import
'INSTANT VB TODO TASK: The following line could not be converted:
import React,
If True Then
useState
End If
from "react"
import
If True Then
useForm
End If
from "react-hook-form"
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'export default @function Home()
'{
' const
' {
' register, handleSubmit, formState:
' {
' errors
' }
' } = useForm();
' const onSubmit = (data) =>
' {
' generatePdf(data);
' };
' const generatePdf = async(data) =>
' {
' try
' {
' console.log("/api/pdf?f=" + data["firstName"]+"&l="+data["lastName"]+"&e="+data["email"]);
' const response = await fetch("/api/pdf-html?f=" + data["firstName"]+"&l="+data["lastName"]+"&e="+data["email"]);
' const blob = await response.blob();
' const url = window.URL.createObjectURL(New Blob([blob]));
' const link = document.createElement("a");
' link.href = url;
' link.setAttribute("download", "awesomeIron.pdf");
' document.body.appendChild(link);
' link.click();
' link.parentNode.removeChild(link);
' }
' catch (@error)
' {
' console.@error("Error generating PDF:", @error);
' }
' };
' const handleChange = (event) =>
' {
' setText(event.target.value);
' };
' Return (<div className={styles.container}> <Head> <title> Generate PDF @Using IronPDF</title> <link rel="icon" href="/favicon.ico" /> </Head> <main> <h1> Demo React Hook Form @and Generate PDF @Using IronPDF</h1> <form onSubmit={handleSubmit(onSubmit)}> <div> <label> First Name</label> {errors.firstName && <span> This field is required</span>} </div> <div> <label> Last Name</label> {errors.lastName && <span> This field is required</span>} </div> <div> <label> Email</label> {errors.email && <span> Invalid email address</span>} </div> <button type="submit" > Submit @and Generate PDF</button> </form> </main> <style jsx>{` main { padding: 5rem 0; flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; } footer { width: 100%; height: 100px; border-top: 1px solid #eaeaea; display: flex; justify-content: center; align-items: center; } footer img { margin-left: 0.5rem; } footer a { display: flex; justify-content: center; align-items: center; text-decoration: none; color: inherit; } code { background: #fafafa; border-radius: 5px; padding: 0.75rem; font-size: 1.1rem; font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier @New, monospace; } `}</style> <style jsx global>{` html, body { padding: 0; margin: 0; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; } * { box-sizing: border-box; } `}</style> </div>);
'}
使用 React Hook 表单库创建一个 React 表单视图,输入名字、姓氏和电子邮件。
创建一个 API,接受用户输入并使用 IronPDF 库生成 PDF。
IronPdf npm 软件包在每个用户的许可证密钥上运行。 IronPDF 提供一个免费试用此外,还需提供许可证,以便用户在购买前了解其丰富的功能。
在使用 IronPDF 软件包之前,请将许可证密钥放在此处:
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
IRON VB CONVERTER ERROR developers@ironsoftware.com
React Hook Form 是一个多功能、高效的库,用于在 React 中处理表单。 其简洁性、性能和灵活性使其成为简单和复杂表单的最佳选择。 无论您是在构建小型项目还是大型应用程序,React Hook Form 都能帮助您轻松管理表单。 IronPDF对于需要以编程方式处理 PDF 文档的 .NET 开发人员来说,《.NET PDF》是一个强大的解决方案。 IronPDF 具有广泛的功能集,包括从各种格式创建 PDF、合并和编辑等操作功能、安全选项、表单创建和格式转换,可简化 PDF 功能与 .NET 应用程序的集成。 其用户友好的 API 和多功能性使其成为在开发项目中有效管理 PDF 任务的重要工具。