使用 Perseid 和 React 建立使用者回饋表
在本指南中,我們將逐步使用 @perseid/form 庫建立動態使用者回饋表單,這是 Formik 和 React Hook Form 的強大替代品。您將看到 @perseid/form 如何輕鬆管理表單狀態、驗證和條件渲染。我們將建立的表單將要求用戶對服務進行評分並提供回饋。根據評級,它會顯示“謝謝”訊息或提示用戶提供其他回饋。
?讓我們開始吧!
第 1 步:設定表單配置
第一步是定義表單配置。此配置概述了表單的行為方式,包括欄位、步驟以及它們之間的流程。在這裡,我們將根據使用者的評分使用 條件邏輯 建立評分和評論欄位。我們還將定義正面和負面回饋的訊息。
這是設定碼:
import { type Configuration } from "@perseid/form"; const formConfiguration: Configuration = { // Root step-the form will start from there. root: "feedback", // Callback triggered on form submission. onSubmit(data) { alert(`Submitting the following JSON: ${JSON.stringify(data)}`); return Promise.resolve(); }, // `fields` define the data model the form is going to deal with. // Expect the submitted data JSON to match this schema. fields: { rating: { type: "integer", required: true, }, review: { type: "string", required: true, // Display this field only if condition is met... condition: (inputs) => inputs.rating !== null && (inputs.rating as number) < 3, }, // Type `null` means that the value of this field will not be included in submitted data. submit: { type: "null", submit: true, }, message_good: { type: "null", }, message_bad: { type: "null", }, }, // Now that fields are defined, you can organize them in a single or multiple steps, // depending on the UI you want to build! steps: { feedback: { fields: ["rating", "review", "submit"], // Whether to submit the form at the end of this step. submit: true, // Next step is conditionned to previous user inputs... nextStep: (inputs) => (inputs.rating as number) < 3 ? "thanks_bad" : "thanks_good", }, thanks_good: { fields: ["message_good"], }, thanks_bad: { fields: ["message_bad"], }, }, };
在此配置:
- 表單從回饋步驟開始。
- 該表單包含兩個欄位:評級(必填)和評論(可選,除非評級低於 3)。
- 根據評級,表單導航至「好」或「壞」回饋訊息。
- 提交表單後,提交的資料會觸發一個簡單的警報。
這裡要掌握的重點是fields屬性的作用。它定義了將提交的資料的結構,本質上充當資料模型。相較之下,steps 屬性概述了表單的流程,決定如何將這些欄位呈現給使用者。
第 2 步:建立表單的 React 元件
現在我們已經有了配置,是時候建立將呈現表單的實際 UI 了。使用@perseid/form/react,我們可以建立自訂欄位元件來管理表單每個部分的使用者互動。
這是核心 React 元件:
import React from "react"; import Form, { type FormFieldProps } from "@perseid/form/react"; // The actual React component, used to build the UI! function Field(props: FormFieldProps): JSX.Element { const { path, engine, value, status } = props; const [currentRating, setCurrentRating] = React.useState(0); // Display a different element depending on the field... if (path === "thanks_good.1.message_good") { return ( <div className="message"> <h1>Thanks for the feedback ?</h1> <p>We are glad you enjoyed!</p> </div> ); } if (path === "thanks_bad.1.message_bad") { return ( <div className="message"> <h1>We're sorry to hear that ?</h1> <p>We'll do better next time, promise!</p> </div> ); } if (path === "feedback.0.rating") { return ( // Depending on the field status, define some extra classes for styling... <div className={`rating ${status === "error" ? "rating--error" : ""}`} onMouseLeave={() => { setCurrentRating((value as number | null) ?? 0); }} > <h1>How would you rate our service?</h1> {[1, 2, 3, 4, 5].map((rating) => ( <span key={rating} className={`rating__star ${ currentRating >= rating ? "rating__star--active" : "" }`} onMouseEnter={() => { setCurrentRating(rating); }} onClick={() => { // On click, notify the form engine about new user input. engine.userAction({ type: "input", path, data: rating }); }} ></span> ))} </div> ); } if (path === "feedback.0.review") { return ( <div className={`review ${status === "error" ? "review--error" : ""}`}> <label>Could you tell us more?</label> <textarea onChange={(e) => engine.userAction({ type: "input", path, data: e.target.value }) } /> </div> ); } // path === 'feedback.0.submit' return ( <button className="submit" onClick={() => { engine.userAction({ type: "input", path, data: true }); }} > Submit </button> ); }
這裡,Field 元件使用 path 屬性決定要渲染什麼:
- 一個評級組件,使用者可以在其中選擇星級。
- 供使用者提供額外回饋的文字區域。
根據評分顯示的「謝謝」訊息。此表單將根據使用者輸入動態調整其欄位和步驟。
很酷,對吧?
第 3 步:運行應用程式
現在我們的表單配置和元件已準備就緒,讓我們將它們整合到一個基本的 React 應用程式中。這是初始化和渲染表單的程式碼:
import { createRoot, type Root } from "react-dom/client"; // Let's run the app! let app: Root; // Creating React root... const container = document.querySelector("#root") as unknown as HTMLElement; app = createRoot(container); app.render( // Router is the main component for any Perseid app. <Form Field={Field} configuration={formConfiguration} /> );
此程式碼使用 React 的 createRoot API 將表單安裝到 DOM。 Form 元件連接我們的配置和 Field 元件,處理其他所有事情。
第四步:新增樣式
好吧,我們有了應用程式邏輯,但是如果您現在運行程式碼,您會發現它有點......原始?
所以,讓我們透過添加一些樣式和動畫來修飾表單!下面是一個簡單的樣式表,使它更具吸引力:
// A few animations for fun... @keyframes swipe-out { 0% { opacity: 1; transform: translateX(0); } 75% { opacity: 0; transform: translateX(-100%); } 100% { opacity: 0; transform: translateX(-100%); } } @keyframes swipe-in-one { 0% { opacity: 0; transform: translateX(100%); } 75% { transform: translateX(0); } 100% { opacity: 1; transform: translateX(0); } } @keyframes swipe-in-two { 0% { opacity: 0; transform: translateX(0); } 75% { transform: translateX(-100%); } 100% { opacity: 1; transform: translateX(-100%); } } @keyframes bubble-in { 0% { transform: scale(0.5); } 75% { transform: scale(1.5); } 100% { transform: scale(1); } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } // Some global basic styling... * { box-sizing: border-box; } body { margin: 0; display: grid; height: 100vh; color: #aaaaaa; align-items: center; font-family: "Helvetica", sans-serif; } // And form-specific styling. .perseid-form { width: 100%; margin: auto; &__steps { display: flex; overflow: hidden; } &__step { min-width: 100%; padding: 1rem 3rem; animation: 500ms ease-in-out forwards swipe-out; &__fields { display: grid; row-gap: 2rem; } } &__step[class*="active"]:first-child { animation: 500ms ease-in-out forwards swipe-in-one; } &__step[class*="active"]:last-child:not(:first-child) { animation: 500ms ease-in-out forwards swipe-in-two; } } .submit { border: none; cursor: pointer; padding: 1rem 2rem; border-radius: 8px; color: #fefefe; font-size: 1.25rem; background: #46c0b0; justify-self: flex-end; transition: all 250ms ease-in-out; &:hover { background: #4cccbb; } } .rating { position: relative; padding: 0.25rem 0; &__star { cursor: pointer; display: inline-block; font-size: 2rem; min-width: 2rem; min-height: 2rem; &::after { content: "⚪️"; } &--active { animation: 250ms ease-in-out forwards bubble-in; &::after { content: "?"; } } } &[class*="error"] { &::after { left: 0; bottom: -1.5rem; color: #f13232; position: absolute; font-size: 0.75rem; content: "? This field is required"; animation: 250ms ease-in-out forwards fade-in; } } } .review { display: grid; row-gap: 1rem; position: relative; animation: 250ms ease-in-out forwards fade-in; label { font-size: 1.25rem; } textarea { resize: none; min-height: 5rem; border-radius: 8px; border: 1px solid #46c0b0; transition: all 250ms ease-in-out; } &[class*="error"] { &::after { left: 0; bottom: -1.5rem; color: #f13232; position: absolute; font-size: 0.75rem; content: "? This field is required"; animation: 250ms ease-in-out forwards fade-in; } } } @media screen and (min-width: 30rem) { .perseid-form { max-width: 30rem; } }
瞧?
結論
恭喜! ?您剛剛使用 Perseid 和 React 建立了一個動態使用者回饋表單。
在本教學中,我們介紹如何:
- 使用條件邏輯定義表單配置。
- 建立自訂 React 元件來處理使用者互動。
- 在您的應用程式中渲染表單並使用動畫和自訂 CSS 對其進行樣式設定。
請隨意嘗試其他欄位和步驟以適合您的用例。享受建立精彩表單的樂趣! ?
- ?更多範例
- ✅ 完整的文檔
- ?加入我們的不和諧
- ?在 GitHub 上為專案加註星標
- ❤️贊助英仙座
以上是使用 Perseid 和 React 建立使用者回饋表的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。
