>本教程解釋了反應事件,受控組件和事件處理,演示瞭如何構建受控形式並從子部門發射數據到父母。 讓我們使用React創建一個用戶配置文件表格。
首先,創建一個新的React應用程序。 位於UserProfile
>中的src/UserProfile.js
組件為用戶配置文件詳細信息提供了一種表單。 將其導入您的根部組件(src/App.js
):
import UserProfile from './UserProfile'; function App() { return ( <div classname="App"> <userprofile></userprofile> </div> ); } export default App;
使用src/App.css
>
.App { text-align: left; margin-left: 20%; margin-right: 20%; } label { display: inline-block; margin-right: 1em; width: 4em; } input { width: 15em; }
渲染表最初將不符合應用程序狀態。 要將表單輸入連接到狀態,我們將使用事件處理程序。
> React事件是由用戶交互或系統事件觸發的操作(單擊,鍵盤,頁面加載等)。 為了處理輸入更改,我們將使用onChange
>事件。 修改name
>UserProfile.js
>的輸入:
<input id="name-field" type="text" value="{name}" onchange="{(e)"> setName(e.target.value)} />同樣,使用其各自的狀態變量和
掛鉤更新email
>,age
和password
>。
useState
登錄狀態,將函數添加到
>
UserProfile.js
const logState = () => { console.log(name); console.log(email); console.log(age); console.log(password); };:
logState
<button onclick="{logState}">Submit</button>發射事件
>要將數據從子(
函數到UserProfile
>:App
>
emit
UserProfile.js
>將提交按鈕更新為
const emit = () => { props.callback({ name, email, age, password }); };
emit
現在,在
<button onclick="{emit}">Submit</button>>:
>:App.js
UserProfile
function App() { const [data, setData] = useState({}); const importData = (data) => setData(data); return ( <div classname="App"> <userprofile callback="{importData}"></userprofile> <p>Name: {data.name || "No name To Display"}</p> <p>Email: {data.email || "No email To Display"}</p> </div> ); }
這完成了教程。 您已經學會瞭如何創建受控組件,處理事件並在React中發射事件。切記用實際的圖像路徑替換佔位符圖像路徑。
以上是理解反應中的形式和事件的詳細內容。更多資訊請關注PHP中文網其他相關文章!