Writing in the front

Communication between React components generally falls into the following categories:

  • Communication between parent and child components
  • Communication between non-nested components

Communication between parent and child components

This is the simplest and most common method of communication: the parent component passes the props to the child component, and the child receives the props and acts on it. Here are two pieces of code:

The parent component fathercom.js:

import React from "react";
import Son from "./SonComp";

export default function FatherComp() {
  return (
    <div>
      <Son title="我就是高阶领主" />
    </div>
  );
}

Copy the code

Child component soncomp.js:

import React from "react";

const Son = (props) => {
  return <h1>{props.title}</h1>;
};

export default Son;
Copy the code

This is not much to say, the most simple passthrough, the next focus on non-nested components communication.

Communication between non-nested components

In short, there is no correlation between components, and we need to have a medium to communicate. Here we use custom events to communicate: first, we need to install an Event package

npm install events --save
Copy the code

Create a new event.js, introduce the Events package, and provide an event object for communication:

import { EventEmitter } from "events";
export default new EventEmitter();
Copy the code

App.js

import React from "react";
import "./styles.css";

import Comp1 from "./Comp1";
import Comp2 from "./Comp2";
import FatherComp from "./FatherComp";

export default function App() {
  return (
    <div>
      <FatherComp />
      <Comp1 />
      <Comp2 />
    </div>
  );
}
Copy the code

Comp1.js

import React, { useState, useEffect } from "react"; import emitter from "./event"; export default function Comp1() { const [msg, setMsg] = useState(null); UseEffect (() => {this.eventEmitter = Emitter.addListener ("clickMe", (MSG) => {setMsg(MSG); }); Return () => {emitter.removelistener (this.eventEmitter); }; } []); Return (<div> {MSG} component 1 </div>); }Copy the code

Comp2.js

import React from "react"; import emitter from "./event"; Export Default function Comp2() {const cb = () => {return () => {// Emit custom events Emitters ("clickMe", "Hello"); }; }; Return (<div> component 2<button onClick={cb()}> </button> </div>); }Copy the code

Let’s write a simple event demo to take a closer look:

On: (name, cb) => {eventPool. Map [name] = cb; }, // emit events: (name,... args) => { const cb = eventPool.map[name]; cb && cb(... args); }}; EventPool. On (" XXX ", (p1, p2) => console.log(p1, p2)); EventPool. Emit (" XXX ", 1, 2); eventPool. Emit (" XXX ", 1, 2); eventPool.Copy the code

conclusion

Custom events in the absence of a direct link between components use is very convenient, anyhow is sweet ~ here is the code involved, this article project address on www.zhangzheyi1.com/2021/07/30/…