组件通信:组件之间的数据传递,根据组件嵌套关系的不同,有不同的通信方法
一、子传父
核心:在子组件中调用父组件的函数并传递实参
import { useState } from "react";
function Son({onGetSonMsg}){
//Son组件中的数据
const sonMsg = 'this is son msg'
return (
<div>
this is son
<button onClick={() => onGetSonMsg(sonMsg)}>sendMsg</button>
</div>
)
}
function App(){
const [msg, setMsg] = useState('')
const getMsg = (msg) => {
console.log(msg);
setMsg(msg)
}
return (
<div>
this is App,{msg}
<Son onGetSonMsg={getMsg}/>
</div>
)
}
export default App
二、父传子
1、父组件传递数据 子组件标签身上绑定属性
2、子组件接收数据,props的参数
function Son(props){
//props:对象里面包含了父组件传递过来的所有的数据
//{ name:'父组件中的数据' }
console.log(props);
// props.name = 'new name'不允许直接修改父组件传递过来的数据,props的数据是只读的,不能修改
return <div>this is son {props.name},jsx:{props.child},{props.children}</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>}>
{/* 当在子组件标签里面嵌套内容时,父组件会自动在名为children的prop属性中接收改内容,即多了个children属性自动传到子组件中 */}
<span>this is children span</span>
</Son>
</div>
)
}
export default App
三、兄弟间通信
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 component,
<button onClick={() => onGetAName(name)}>send</button>
</div>
)
}
function B({name}){
return (
<div>
this is B component,
{name}
</div>
)
}
function App(){
const [name,setName] = useState('')
const getName = (name) => {
console.log(name);
setName(name)
}
return(
<div>
this is App
<A onGetAName={getName} />
<B name={name} />
</div>
)
}
export default App
四、爷孙组件传递数据
App -> A -> B 1、createContext方法创建一个上下文对象 2、在顶层组件通过Provider组件提供数据 3、在底层组件通过useContext钩子函数使用数据
import { createContext, useContext } from "react"
const MsgContext = createContext()
function A(){
return(
<div>
this is A component
<B/>
</div>
)
}
function B(){
const msg = useContext(MsgContext)
return (
<div>
this is B component,{msg}
</div>
)
}
function App(){
const msg = 'this is app msg'
return (
<div>
<MsgContext.Provider value={msg}>
this is App
<A/>
</MsgContext.Provider>
</div>
)
}
export default App