父传子
- 父组件传递数据 子组件标签上绑定属性
- 子组件接受数据 props的参数
- props 可传递任意的数据,包括函数、标签、对象、JSX…
- props 数据再子组件中是只读的,父组件数据只能父组件修改
- 当在子组件标签中填写时,会自动在props使用children将标签内信息填写进去
function Son(props) {
//props中包含父组件传递的所有数据
console.log(props)
return <div>this is son</div>
}
function APP() {
const name = 'this is app name'
const age = 18
return(
<div>
<Son
name={name}
age={age}
cb={()=>console.log(123)}
child={<span>child span</span>}
/>
<Son>
<span>child span</span>
</Son>
</div>
)
}
子传父
利用父组件函数传递数据
function Son({onGetSonMsg}) {
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>
{msg}
<Son onGetSonMsg={getMsg}/>
</div>
)
}
兄弟组件通信
借助’状态提升‘机制,通过父组件进行兄弟组件之间的数据传递
- 子传父 A->App
- 父传子 App->B
function A({onGetAname}) {
const name = "this is A name"
return (
<div>
this is A
<button onClick={()=>onGetAname(name)}>send</button>
</div>
)
}
function B({name}) {
return (
<div>
this is B
{name}
</div>
)
}
function APP() {
const [name,setName]=useState('')
const getAName = (name)=> {
console.log(name)
}
return(
<div>
this is APP
<A onGetAName={getAName}/>
<B name={name}/>
</div>
)
}
跨层级组件通信
- 使用
createContext
方法创建一个上下文Ctx
- 在顶层组件(APP)中通过
Ctx.Provider
组件提供数据 - 在底层组件(B)中通过
useContext
钩子函数获取消费数据
//使用createContext方法(React)创建一个上下文Ctx
const MsgContext = createContext()
function A({onGetAname}) {
const name = "this is A name"
return (
<div>
this is A
<B/>
</div>
)
}
function B({}) {
const msg = useContext(MsgContext)
return (
<div>
this is B
{msg}
</div>
)
}
function APP() {
const msg = 'this is app msg'
return(
<div>
<MsgContext.Provider value={msg}>
this is APP
<A />
</MsgContext.Provider>
</div>
)
}
除了上述提到的还有利用全局变量,Portal,Observe Pattern,Redux等方式也能实现组件间通信,这里就简述几种常用方法。