在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
React Hook Form 是一個強大且高效的庫,用於管理 React 應用中的表單值。 它利用 React hooks 提供無需控制器組件的無縫且高效的體驗。 在本文中,我們將探討使用自定義錯誤訊息提交 React Hook Form 的基礎知識及其優點,並提供程式碼示例幫助您入門。
性能: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:第一步是創建一個後端 API 來生成 PDF 文件。 由於 IronPDF 只在伺服器端運行,我們需要創建一個 API,供用戶在需要生成 PDF 時調用。 在路徑 pages/api/pdf.js 中創建一個文件,並添加以下內容。
IronPDF需要許可金鑰,您可以從授權頁面```html <!DOCTYPE html>
IronPDF 是一個功能強大的.NET PDF庫,使得生成和編輯PDF文件變得簡單。無論您使用的是C#、VB.NET還是JavaScript,IronPDF都能滿足您的需求。
IronOCR 是一個領先的.NET光學字符識別庫,能夠準確地將圖像轉換為可編輯的文本。這個工具對於需要處理大量掃描文件的開發人員來說非常有用。
IronXL 提供了一個強大的Excel讀取和寫入庫,簡化了處理Excel文件的流程。無論是讀取、修改還是生成,IronXL都能夠輕鬆完成。
IronBarcode and IronQR 能夠快速生成和讀取條形碼和二維碼,適合各種應用場景。
IronZIP 是一個.NET庫,用於創建、編輯和提取ZIP文件,支持高效的文件壓縮和解壓。
IronWord 提供了一個靈活的工具來生成、編輯和閱讀Word文件。它支持所有的Word格式,使得文檔處理變得簡單和可靠。
IronPrint 是一個強大的打印庫,能夠輕鬆地從任何.NET應用程序進行打印操作。
IronWebscraper 是一個方便的工具,可以從Web頁面中提取數據,適用於數據收集和分析。
Iron Suite 包含了所有的Iron Software工具包,提供全面的解決方案,以滿足您的所有需求。
```cs
// 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();
}
}
現在修改 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 Form 庫創建一個 React 表單視圖,來輸入名字、姓氏和電子郵件。
使用IronPDF庫創建一個API來接收用戶輸入並生成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是.NET開發人員需要以程式方式處理PDF文件的強大解決方案。 IronPDF 擁有廣泛的功能集,包括從各種格式創建 PDF、合併和編輯等操作功能、安全選項、表單創建和格式轉換,使得 PDF 功能的整合進入 .NET 應用程式變得更加高效。 其用戶友好的 API 和多功能性使其成為在開發項目中高效管理 PDF 任務的寶貴工具。