React组件通信

父传子

  1. 父组件传递数据 子组件标签上绑定属性
  2. 子组件接受数据 props的参数
  3. props 可传递任意的数据,包括函数、标签、对象、JSX…
  4. props 数据再子组件中是只读的,父组件数据只能父组件修改
  5. 当在子组件标签中填写时,会自动在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>
	) 
}

兄弟组件通信

借助’状态提升‘机制,通过父组件进行兄弟组件之间的数据传递
image.png

  1. 子传父 A->App
  2. 父传子 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>
	) 
}

跨层级组件通信

  1. 使用createContext方法创建一个上下文Ctx
  2. 在顶层组件(APP)中通过Ctx.Provider组件提供数据
  3. 在底层组件(B)中通过useContext钩子函数获取消费数据

image.png

//使用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等方式也能实现组件间通信,这里就简述几种常用方法。

  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值