React non-nested component communication

Non-nested component: is a component without any inclusion relationship, including sibling components and non-brother components that are no longer the same parent For component communication in this case, there are two ways to handle

to communicate with the context object of the common parent component. List content Custom event mode for communication

The first method uses a context object similar to a global variable, which may cause global pollution. The official recommendation is not to use it as much as possible.

The way, in fact, is also very simple, similar to the way service dependency injection in angular. This method requires the use of event packages with custom events, which are installed first. Javascript code

npm install event -S

or

yarn add event

Component structure: App component is the root component, there are two sibling components in the root component, Child1, Child2, Event service for communication between Child1 and Child2 components. The Child1 component is implemented below. Communication with the Child2 component

Event.js (service) Javascript code

import {EventEmitter} from 'events'; / / This does not use the syntax of jsx, so do not import React

export default new EventEmitter (); App component Javascript code

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Child1 from './views/Child1'; import Child2 from './views/Child2';

class App extends Component {   render() {     return (       <div className="App">         <header className="App-header">           <img src={logo} className="App-logo" alt="logo" />           <h1 className="App-title">Welcome to React</h1>         </header>

        <Child1 />         <Child2 />       </div>     );   } }

export default App;

Child1 component Javascript code

import React, {Component} from 'react'; import emitter from '../services/event';

class Child extends Component {     constructor() {         super();         this.handleClick = this.handleClick.bind(this);     }     handleClick() {         emitter.emit('callMe', 'Hello');     }     render() {         return (             <button onClick={this.handleClick}>event click</button>               );     } }

export default Child;

Child2 component Javascript code

import React, {Component} from 'react'; import emitter from '../services/event';

class Parent extends Component {     constructor() {         super();     }     componentDidMount() {         this.eventEmitter = emitter.addListener('callMe', (msg) => {             console.log(msg);         });     }     componentWillUnmount() {         emitter.removeListener(this.eventEmitter);     }     render() {         return (             <p>Parent Component</p>         );     } }

export default Parent;