在 React 中,可以使用 受控元件 或 非受控元件 來管理輸入欄位、複選框和文字區域等表單元素。這兩種方法提供了不同的方法來處理和更新表單數據,了解它們之間的差異對於為您的 React 應用程式選擇正確的方法至關重要。
在受控元件中,表單元素由React元件的狀態控制。表單資料透過 React 的狀態進行管理,使用者所做的任何變更都會反映在元件的狀態中。 React 元件可作為表單資料的「單一事實來源」。
import React, { useState } from 'react'; const ControlledForm = () => { const [inputValue, setInputValue] = useState(''); const handleChange = (e) => { setInputValue(e.target.value); // Update the state with the user input }; return ( <form> <input type="text" value={inputValue} // Value is controlled by React state onChange={handleChange} // Updates state on user input /> <button type="submit">Submit</button> </form> ); }; export default ControlledForm;
在不受控制的元件中,表單元素由 DOM 本身管理,而不是由 React 的狀態管理。 React 不直接追蹤表單元素的值。相反,您可以使用 refs(引用)來存取 DOM 元素並檢索其當前值。
import React, { useState } from 'react'; const ControlledForm = () => { const [inputValue, setInputValue] = useState(''); const handleChange = (e) => { setInputValue(e.target.value); // Update the state with the user input }; return ( <form> <input type="text" value={inputValue} // Value is controlled by React state onChange={handleChange} // Updates state on user input /> <button type="submit">Submit</button> </form> ); }; export default ControlledForm;
Feature | Controlled Components | Uncontrolled Components |
---|---|---|
State Management | Data is managed by React’s state. | Data is managed by the DOM, using refs. |
Data Flow | Value is passed as a prop and updated via state. | Value is accessed directly through the DOM. |
Form Validation | Easy to validate and control form data in real-time. | Validation is more complex and may require additional handling. |
Boilerplate Code | Requires more code to manage state and updates. | Less boilerplate code but requires refs for accessing form data. |
Performance | May be slower with a large number of form elements. | Faster for large forms or when you don’t need real-time data updates. |
Complexity | Offers more flexibility and control over form behavior. | Simpler and more straightforward for simple forms. |
在以下情況下,受控組件是首選:
不受控制的組件較適合以下情況:
受控元件和非受控元件在 React 應用程式中都佔有一席之地。受控組件提供了更好的控制和可預測性,使其成為最複雜形式的理想選擇。然而,對於基本表單或當您不需要即時控制資料時,不受控制的元件可能是更簡單、效能更有效率的解決方案。
了解何時使用每種類型的元件將幫助您根據特定用例確定最佳方法。
以上是React 中的受控元件與非受控元件:選擇正確的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!