?? 如果還不了解 HTML 、 CSS和JS,可以參考本號(hào)下的 HTML21 天入門教程、 CSS 21 天入門教程和JS21天入門教程。
React 開發(fā)是基于組件的,也就大功能會(huì)拆分成一個(gè)一個(gè)小功能,也就變成了一個(gè)個(gè)組件。
很自然的,組件之間就存在父子關(guān)系、兄弟關(guān)系及跨級(jí)關(guān)系三種。
今天來講父子組件之間的通信。
父子組件通信
父子組件之間的通信分成父到子、子到父兩種。
父到子通信
父組件到子組件的通信,在前面講屬性的時(shí)候提過。
通過 props
,可以把數(shù)據(jù)從父組件傳遞到子組件。
這時(shí)候傳遞到子組件的數(shù)據(jù)是只讀的。
import React from 'react'; function SayHello(props) { return ( <div> <h1>Hello, {props.name}!</h1> </div> ); } export default SayHello;
上面的 SayHello
組件是一個(gè)子組件,它接受來自父組件的屬性 name
。
import SayHello from './SayHello'; function App() { return ( <SayHello name="World" /> } export default App;
在上面的父組件 App
中,傳入屬性 name
給子組件。
這種父到子的數(shù)據(jù)傳遞,類似于函數(shù)調(diào)用時(shí)候的參數(shù)傳遞。
子到父通信
子組件到父組件的數(shù)據(jù)傳遞,還是通過 props
實(shí)現(xiàn)的。
依然是通過 props
從父組件向子組件先傳遞,不同的是傳遞是回調(diào)函數(shù),而不是具體的數(shù)據(jù)。
因?yàn)閿?shù)據(jù)在子組件是不能修改的,但回調(diào)函數(shù)則可以傳遞信息回去在父組件執(zhí)行。
import React from 'react'; function SayHello(props) { const sendMessage = () => { const message = 'Hello from child!'; props.onMessage(message); }; return ( <div> <h1 style={{ color: 'blue', fontSzie: 22 }}>Hello, {props.name}!</h1> <button onClick={sendMessage}>發(fā)送消息</button> </div> ); } export default SayHello;
修改上述子組件代碼,增加了一個(gè)按鈕。并且按鈕有點(diǎn)擊事件。
在點(diǎn)擊事件里,為 props
的 onMessage
方法傳遞了 message
信息。
import './App.css'; import SayHello from './SayHello'; import { useState } from 'react'; function App() { const [msg, setMsg] = useState(''); const handleChildMessage = (message) => { setMsg(message); console.log('Received message from child:', message); }; return ( <div> <div>{msg}</div> <SayHello name="World" onMessage={handleChildMessage} /> </div> ); } export default App;
修改父組件代碼,在子組件的調(diào)用上,增加了剛才新添加的事件 onMessage
事件處理方法 handleChildMessage
。
在 handleChildMessage
方法,把接收到的 message
和頁面中 div
顯示的內(nèi)容綁定在一起。
這樣的實(shí)現(xiàn)效果如下:
?
總結(jié)
最后來總結(jié)一下今天的內(nèi)容要點(diǎn):
- ?? 組件之間存在父子關(guān)系、兄弟關(guān)系及跨級(jí)關(guān)系三種。
- ?? 父子組件之間的通信由
props
傳遞完成。
該文章在 2024/12/13 8:56:38 編輯過