父傳子
實現步驟
- 父組件傳遞數據 - 在子組件標簽上綁定屬性
- 子組件接收數據 - 子組件通過props參數接收數據
// 父傳子
// 1. 父組件傳遞數據 子組件標簽身上綁定屬性
// 2. 子組件接收數據 props的參數
function Son (props) {
// props:對象里面包含了父組件傳遞過來的所有的數據
// { name:'父組件中的數據'}
console.log(props)
return (
<div>
<h2>子組件接收的數據父組件:</h2>
<div>我也姓:{props.xingshi}</div>
</div>
)
}
function App () {
const xingshi = 'zhang'
return (
<div>
<h1>父組件的數據:</h1>
<div>我姓:{xingshi}</div>
<Son xingshi={xingshi}/>
</div>
)
}
export default App

image.png
props說明
props可以傳遞任意的合法數據,比如數字、字符串、布爾值、數組、對象、函數、JSX
function Son (props) {
console.log(props)
return <div>this is son, {props.name}, jsx: {props.child}</div>
}
function App () {
const name = 'this is app name'
return (
<div>
<Son
name={name}
age={18}
isTrue={false}
list={['vue', 'react']}
obj={{ name: 'jack' }}
cb={() => console.log(123)}
child={<span>this is span</span>}
/>
</div>
)
}
export default App

image.png
props是只讀對象
子組件只能讀取props中的數據,不能直接進行修改, 父組件的數據只能由父組件修改
特殊的prop-chilren
場景:當我們把內容嵌套在組件的標簽內部時,組件會自動在名為children的prop屬性中接收該內容

image.png
審查元素查看

image.png
子傳父

image.png
核心思路:在子組件中調用父組件中的函數并傳遞參數
import { useState } from "react"
function Son ({ onGetSonMsg }) {
// Son組件中的數據
const sonMsg = '來自子組件的數據'
return (
<div>
這是子組件
<button onClick={() => onGetSonMsg(sonMsg)}>獲取子組件的數據</button>
</div>
)
}
function App () {
const [msg, setMsg] = useState('')
const getMsg = (msg) => {
console.log(msg)
setMsg(msg)
}
return (
<div>
父組件: {msg}
<Son onGetSonMsg={getMsg} />
</div>
)
}
export default App
兄弟組件通信

image.png
實現思路: 借助
狀態(tài)提升 機制,通過共同的父組件進行兄弟之間的數據傳遞
- A組件先通過子傳父的方式把數據傳遞給父組件App
- App拿到數據之后通過父傳子的方式再傳遞給B組件
// 1. 通過子傳父 A -> App
// 2. 通過父傳子 App -> B
import { useState } from "react"
function A ({ onGetAName }) {
// Son組件中的數據
const name = 'this is A name'
return (
<div>
this is A compnent,
<button onClick={() => onGetAName(name)}>send</button>
</div>
)
}
function B ({ name }) {
return (
<div>
this is B compnent,
{name}
</div>
)
}
function App () {
const [name, setName] = useState('')
const getAName = (name) => {
console.log(name)
setName(name)
}
return (
<div>
this is App
<A onGetAName={getAName} />
<B name={name} />
</div>
)
}
export default App

image.png
跨層組件通信

09.png
實現步驟:
- 使用
createContext方法創(chuàng)建一個上下文對象Ctx - 在頂層組件(App)中通過
Ctx.Provider組件提供數據 - 在底層組件(B)中通過
useContext鉤子函數獲取消費數據
// App -> A -> B
import { createContext, useContext } from "react"
// 1. createContext方法創(chuàng)建一個上下文對象
const MsgContext = createContext()
// 2. 在頂層組件 通過Provider組件提供數據
// 3. 在底層組件 通過useContext鉤子函數使用數據
function A () {
return (
<div>
這個是組件A
<B />
</div>
)
}
function B () {
const msg = useContext(MsgContext)
return (
<div>
<div>這個是組件B:</div>
<div>{msg}</div>
</div>
)
}
function App () {
const msg = '頂級組件傳遞數據給B組件'
return (
<div>
<MsgContext.Provider value={msg}>
這個是頂級組件 App
<A />
</MsgContext.Provider>
</div>
)
}
export default App

image.png