一、event bus 事件总线 进行非父子组件间的通信(兄弟组件)
yarn add -D events
Main.js-==》Header.js
APP.js------------------------------------------------------------------------------
import React, { Component } from 'react';
import Header from './Header';
import Main from './Main';
export default class App extends Component {
render() {
return (
<div>
{/* 兄弟组件 */}
<Header />
<Main />
</div>
);
}
}
Main.js组件------------------------------------------------------------------------------
import React, { Component } from 'react'
import eventBus from './event'
export default class Main extends Component {
render() {
return (
<div>
<h2>Main组件</h2>
<button onClick={e => this.emitter()}>发送事件</button>
</div>
)
}
emitter() {
const obj = {
name: '芳芳老师',
age: 19
}
const n = 123;
//发送sayHello事件,并且传递obj,n
eventBus.emit('sayHello', obj, n);
}
}
Header.js组件------------------------------------------------------------------------------
import React, { Component } from 'react'
import eventBus from './event'
export default class Header extends Component {
//监听sayHello事件
componentDidMount() {
eventBus.addListener('sayHello', this.handleSayHello);
}
//处理事件监听
handleSayHello(obj, n) {
console.log(obj, n);
}
//移除事件监听
componentWillUnmount() {
eventBus.removeListener('sayHello', this.handleSayHello);
}
render() {
return (
<div>
<h1>Header组件</h1>
</div>
)
}
}
二、Context的应用场景:在于很多不同层级的组件需要访问同样一些的数据,谨慎使用,因为这样会使得组件的复用性变差
祖先==》所有后代
import React, { Component } from 'react'
const obj = {
name: '方方',
age: 18
}
//为Father组件创建context()对象,传入一个默认值
const FatherContext = React.createContext(obj);
class Child extends Component {
// context对象赋值给contextType属性
//可以通过this.context去使用context的值
static contextType = FatherContext;
render() {
console.log(this.context);
return (
<div>
我是儿子组件,接到的值为:
<h3>{this.context.name}</h3>
<h3>{this.context.age}</h3>
</div>
)
}
}
//函数式类
function Father() {
return (
<FatherContext.Consumer>
{
value => (
<div>我是父亲组件接到的值为:
<h3>{value.name}</h3>
<h3>{value.age}</h3>
<Child />
</div>
)
}
</FatherContext.Consumer>
)
}
export default class App extends Component {
constructor() {
super();
this.state = {
name: '星星星星',
age: 24
}
}
//用Provide将当前的state传递给下级组件
render = () => (
<div>
我是爷爷组件
<FatherContext.Provider value={this.state}>
<Father />
</FatherContext.Provider>
</div >
)
}
三、props父子组件通信
props一层一层的传
import React, { Component } from 'react';
// 父组件
export default class App extends Component {
render() {
return (
<div>
{/* 通过一个props去传递,传递一个属性,它的值是一个方法 */}
<Profile money='父传子' customize={(str) => { this.CustomEvent(str); }} />
</div>
);
}
// CustomEvent
CustomEvent(str) {
console.log(str);
}
}
// 子组件
class Profile extends Component {
constructor(props) {
console.log(props);
super(props);
this.state = {
name: '芳芳老师',
};
}
render() {
return (
<div>
<h2>profile</h2>
<button onClick={(e) => { this.getString(this.state.name); }}>点击</button>
</div>
);
}
getString(str) {
const { customize } = this.props;
customize(str);
}
}