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>
);
}
}
react onRef使用,通过onRef实现同级组件通讯
于 2022-09-06 16:10:56 首次发布