react onRef使用,通过onRef实现同级组件通讯

import React, { Component } from 'react'
import {Button} from 'antd'


export default class Home extends React.Component {
	constructor(props) {
	 super(props);
	 this.state = {};
	}

	// 1. 创建两个ref,并指向他们的实力
	// 2. 将实例互相指向对方,同时在生命周期函数进行绑定到props
	// 3. 然后通过props进行调用,注意下面这个位置,其实返回的是一个方法,这样你才能通过props去点击调用
	// ```
	// <Brother2 onRef={this.onRef2} onClick={()=>{this.brother1.changeMsg && this.brother1.changeMsg('来自组件Brother2中的数据')}} />
	// ```


	onRef1=(ref)=>{
	 	this.brother1=ref;
	}

	onRef2=(ref)=>{
	 	this.brother2=ref;
	}

	getFn1 = () =>{
		let msg = this.brother2.getText()
		console.log(msg, 'brother1')
	}
	getFn2 = () =>{
		let msg = this.brother1.getText()
		console.log(msg, 'brother2')
	}

	
	render() {
	 return (
	  <div className="home">
		<div><Button onClick={this.getFn1}>getBrother1</Button><Button onClick={this.getFn2}>getBrother2</Button></div>
	   <Brother1 onRef={this.onRef1} onClick={
		()=>{
		 this.brother2.changeMsg && this.brother2.changeMsg('来自组件Brother1中的数据')
		}
	   }/>
	   <Brother2 onRef={this.onRef2} onClick={
		()=>{
		 this.brother1.changeMsg && this.brother1.changeMsg('来自组件Brother2中的数据')
		}
	   } />
	   </div>
	 );
	}
   }


   class Brother2 extends React.Component {
	constructor(props) {
	 super(props);
	 this.state = {
		text: 'Brother2'
	 };
	}
	componentDidMount(){
		this.props.onRef && this.props.onRef(this)
	}

	getText =() =>{
		return '我是来自brother2的数据'
	}

	changeMsg=(val)=>{
		this.setState({
		 text:'Brother2数据变了'+'---->'+val + Math.random()
		})
	   }
	
	render() {
	 return (
		<div>
			<button onClick={this.props.onClick}>Brother2去修改Brother1中的数据</button>--------><span>{this.state.text}</span>	
		</div>
	 );
	}
   }


   class Brother1 extends React.Component {
	constructor(props) {
	 super(props);
	 this.state = {
	  text:'Brother1'
	 };
	}
	componentDidMount(){
		this.props.onRef&&this.props.onRef(this)
	   }
	   
	changeMsg=(val)=>{
	 this.setState({
	  text:'Brother1数据变了'+'---->'+ val + Math.random()
	 })
	}

	getText =() =>{
		return '我是来自brother1的数据'
	}

	render() {
	 return (
	  <div>
		<div ><button onClick={this.props.onClick}>Brother1去修改Brother2中的数据</button>--------><span>{this.state.text}</span>	</div>
	</div>
	 );
	}
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值