本教程詳細(xì)講解如何在React中實(shí)現(xiàn)子組件向父組件傳遞數(shù)據(jù)。通過在父組件定義回調(diào)函數(shù)并作為props傳遞給子組件,子組件在事件觸發(fā)時(shí)調(diào)用該回調(diào),將數(shù)據(jù)回傳。父組件使用狀態(tài)管理接收數(shù)據(jù),并可利用`useEffect`響應(yīng)數(shù)據(jù)變化,實(shí)現(xiàn)動態(tài)數(shù)據(jù)請求,避免直接調(diào)用組件函數(shù)。
在React應(yīng)用開發(fā)中,組件之間的數(shù)據(jù)流通常是單向的,即數(shù)據(jù)從父組件流向子組件(通過props)。然而,在許多場景下,我們需要子組件將數(shù)據(jù)或事件通知給父組件。例如,一個(gè)表單輸入組件(子組件)在用戶提交數(shù)據(jù)后,需要將輸入值傳遞給其父組件進(jìn)行處理。本文將以一個(gè)具體的示例,詳細(xì)闡述如何實(shí)現(xiàn)這種“子組件向父組件傳遞數(shù)據(jù)”的通信模式。
React的核心思想是單向數(shù)據(jù)流。父組件通過props將數(shù)據(jù)傳遞給子組件。當(dāng)子組件需要與父組件通信時(shí),它不能直接修改父組件的狀態(tài)。正確的做法是,父組件傳遞一個(gè)回調(diào)函數(shù)給子組件作為prop,子組件在需要通信時(shí)調(diào)用這個(gè)回調(diào)函數(shù),并將數(shù)據(jù)作為參數(shù)傳遞給它。這樣,父組件就能在其回調(diào)函數(shù)中接收到子組件傳來的數(shù)據(jù),并更新自己的狀態(tài)。
假設(shè)我們有一個(gè)InputField組件用于用戶輸入地址,并有一個(gè)App組件作為主應(yīng)用,需要在InputField提交數(shù)據(jù)后,使用該地址進(jìn)行API請求。
首先,我們需要修改InputField組件,使其能夠接收一個(gè)回調(diào)函數(shù)作為prop。當(dāng)用戶提交表單時(shí),InputField會調(diào)用這個(gè)回調(diào)函數(shù),并將輸入值傳遞出去。
// InputField.js import React from 'react'; export default function InputField({ onSubmit }) { // 接收一個(gè)名為 onSubmit 的 prop function handleSubmit(e) { e.preventDefault(); // 阻止瀏覽器默認(rèn)的表單提交行為 const form = e.target; const inputVal = form.myInput.value; // 獲取輸入框的值 console.log("子組件獲取到的輸入值:", inputVal); // 調(diào)用父組件傳遞進(jìn)來的回調(diào)函數(shù),并將輸入值作為參數(shù)傳遞 if (onSubmit && typeof onSubmit === 'function') { onSubmit(inputVal); } } return ( <form method="post" onSubmit={handleSubmit}> <input name="myInput" id="adress-field" placeholder="Enter adress" autoComplete="on" /> <button type="submit" id="adress-button">Send</button> </form> ); }
關(guān)鍵點(diǎn):
接下來,我們需要在App組件中定義一個(gè)狀態(tài)來存儲從InputField接收到的數(shù)據(jù),并創(chuàng)建一個(gè)回調(diào)函數(shù)傳遞給InputField。
// App.js import './App.css'; import AccountNumber from "./components/AccountNumber"; import InputField from "./components/InputField"; import { useEffect, useState } from "react"; function App() { // 狀態(tài)用于存儲從 InputField 接收到的地址值 const [searchValue, setSearchValue] = useState(null); // 狀態(tài)用于存儲API返回的tokens數(shù)據(jù) const [tokens, setTokens] = useState([]); // 狀態(tài)用于管理加載狀態(tài) const [loading, setLoading] = useState(false); // 定義一個(gè)回調(diào)函數(shù),用于接收 InputField 傳遞過來的值 const handleSearchSubmit = (val) => { setSearchValue(val); // 更新 searchValue 狀態(tài) }; // useEffect 鉤子用于在 searchValue 變化時(shí)觸發(fā)數(shù)據(jù)請求 useEffect(() => { // 只有當(dāng) searchValue 不為 null 且不為空字符串時(shí)才進(jìn)行數(shù)據(jù)請求 if (searchValue) { setLoading(true); fetch(`https://api.multiversx.com/accounts/${searchValue}/tokens`) .then(response => response.json()) .then(json => setTokens(json)) .finally(() => { setLoading(false); }); console.log("App組件發(fā)起請求,searchValue:", searchValue); } // 依賴數(shù)組包含 searchValue,確保當(dāng) searchValue 改變時(shí) useEffect 重新運(yùn)行 }, [searchValue]); // ... (其他輔助函數(shù),如 round, numberWithSpaces 保持不變) return ( <content className="content"> <div className="up-side"> <div className="account-number-box"> <p id="p-account-number">Total number of accounts</p> <p id="account-number"><AccountNumber/></p> </div> <div className="adress-search"> {/* 將 handleSearchSubmit 函數(shù)作為 onSubmit prop 傳遞給 InputField */} <InputField onSubmit={handleSearchSubmit} /> </div> {/* 可以顯示當(dāng)前 searchValue 進(jìn)行調(diào)試 */} <p>當(dāng)前搜索地址: {searchValue || '未輸入'}</p> </div> <div className="down-side"> <table className="Token-section-output"> {loading ? ( <div>Loading...</div> ) : ( <> <h1>Tokens</h1> <table className='Token-section-output' border={0}> <tr className='token-row-type'> <th className='token-column'>Name</th> <th className='center-column'>Price</th> <th>Hold</th> </tr> <tr className="space20"/> {tokens.map(token => ( <tr className='token-row' key={token.id}> <td className='token-column'> <img className="img-Tokens" src = {token?.assets?.pngUrl ?? "img/Question.png"} /> <p>{token.name}</p> </td> <td className='center-column'> <p>${round(token.price, 10000000)}</p> </td> <td> <p>{round(token.balance / Math.pow(10, token.decimals), 10000000)}</p> <p className='token-hold'>${round(token.valueUsd, 10000000)}</p> </td> </tr> ))} </table> </> )} </table> </div> </content> ); } // 輔助函數(shù)(保持不變) function round(nr, ten) { return Math.round(nr * ten) / ten; } function numberWithSpaces(nr) { return nr.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " "); } export default App;
關(guān)鍵點(diǎn):
通過以上步驟,我們成功地實(shí)現(xiàn)了React中子組件向父組件傳遞數(shù)據(jù)的功能。這種模式是React應(yīng)用中組件間通信的基石,被稱為“提升狀態(tài)”(Lifting State Up)。
核心概念回顧:
注意事項(xiàng):
掌握這種通信模式對于構(gòu)建復(fù)雜的、交互性強(qiáng)的React應(yīng)用至關(guān)重要。
以上就是React組件間通信:從子組件向父組件傳遞數(shù)據(jù)實(shí)踐的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個(gè)人都需要一臺速度更快、更穩(wěn)定的 PC。隨著時(shí)間的推移,垃圾文件、舊注冊表數(shù)據(jù)和不必要的后臺進(jìn)程會占用資源并降低性能。幸運(yùn)的是,許多工具可以讓 Windows 保持平穩(wěn)運(yùn)行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號