首先介绍一下跨组件通讯的之间的关系,如下图:

React-跨组件通讯_React

父子通讯

如果我们想在爷爷组件当中给儿子进行通讯,那么该如何进行实现呢,首先来看第一种方式就是一层一层的传递,为了方便观察这里博主就直接都定义在一个文件当中, 先来看从爷爷给到儿子方法的这么一个过程:

App.js:

import React from 'react';
import './App.css';

class App extends React.Component {
render() {
return (
<div>
爷爷
<Father grandpaFunction={this.grandpaFunction.bind(this)}/>
</div>
)
}

grandpaFunction() {
console.log('BNTang');
}
}

class Father extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<div>
爸爸
<Son grandpaFunction={this.props.grandpaFunction}/>
</div>
)
}
}

class Son extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<div>
儿子
<button onClick={() => this.sonFn()}>儿子组件按钮</button>
</div>
)
}

sonFn() {
this.props.grandpaFunction();
}
}

export default App;

React-跨组件通讯_代码实现_02

然后在来看一个儿子像父组件通讯的这么一个过程:

App.js:

import React from 'react';
import './App.css';

class App extends React.Component {
render() {
return (
<div>
爷爷
<Father grandpaFunction={this.grandpaFunction.bind(this)}/>
</div>
)
}

grandpaFunction(name, age) {
console.log(name, age);
}
}

class Father extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<div>
爸爸
<Son grandpaFunction={this.props.grandpaFunction}/>
</div>
)
}
}

class Son extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<div>
儿子
<button onClick={() => this.sonFn()}>儿子组件按钮</button>
</div>
)
}

sonFn() {
this.props.grandpaFunction('BNTang', 18);
}
}

export default App;

如上的这个栗子主要是演示了一下左边这一块的通讯,如下图:

React-跨组件通讯_代码实现_03

兄弟通讯

兄弟之间通讯不能直接进行,需要先与父组件通讯,然后父组件在和另外一个组件进行通讯传递对应的数据到达对应的兄弟组件当中完成通讯,结构图如下:

React-跨组件通讯_数据_04

代码实现,App.js:

import React from 'react';
import './App.css';

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
age: undefined
}
}

render() {
return (
<div>
<A appFn={this.appFn.bind(this)}/>
<B name={this.state.name} age={this.state.age}/>
</div>
)
}

appFn(name, age) {
this.setState({
name: name,
age: age
});
}
}

class A extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<div>
兄弟A
<button onClick={() => {
this.aFn()
}}>兄弟A的按钮</button>
</div>
)
}

aFn() {
this.props.appFn('BNTang', 18);
}
}

class B extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<div>
兄弟B
<p>兄弟B:{this.props.name}</p>
<p>兄弟B:{this.props.age}</p>
</div>
)
}
}

export default App;

React-跨组件通讯_css_05