React component communication

Posted by Allan- on Sun, 08 Sep 2019 19:07:54 +0200

Preface

Previous articles have introduced the basics of React, and this article will also document how components in React communicate through an instance.

If there are any mistakes or omissions in the article, please also see the little partner give more advice and thank you first.

Below_

In React, there are several situations where component communication is required:

  • Parent components communicate to child components
  • Child components communicate with parent components
  • Cross-level component communication
  • Non-nested component communication

Parent components communicate to child components

React It is also common for a parent component to transfer data to a child component by using a one-way flow of data. props Transfer data to subcomponents

Example Demo

// Parent Component
class App extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (
            <Child name='tadpole' />
        )
    }
}

// Subcomponents
function Child(props) {
    return (
        <div>{props.name}</div>
    )
}

Child components communicate with parent components

Trigger callbacks using custom events

Instance Demo

// Parent Component
class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {data: ''}
    }
    // Custom Callback Events
    childValue = data => {
        this.setState({data})
    }
    render() {
        return (
            <div>
                //Value passed by subcomponent: {this.state.data}
                <Child transferValue={this.childValue}/>
            </div>
        )
    }
}

// Subcomponents
class Child extends React.Component {
    constructor(props) {
        super(props)
        this.state = {data: ''}
    }
    valueChange = data => {
        // Keep values in subcomponents consistent with values passed in the past
        this.setState({
            data: data.target.value
        })
        // Trigger callback passed to parent component
        this.props.transferValue(data.target.value)
    }
    render() {
        return (
            <div>
                //Sub-component: <input vlaue={this.state.data} onChange={this.valueChange} />
            </div>
        )
    }
}

Cross-level component communication

  • Pass props one layer at a time
  • Context

React follows the rule of one-way data flow (top-down), in fact, we can completely achieve the purpose of cross-level communication by passing props through each level of components.However, during this process, some components do not need to use props passed by their superiors, which is undoubtedly redundant, and Context was introduced

Context Provides a layer-by-layer component that does not need to be added manually props,A way to transfer data between component trees is designed to share data that is "global" to a component tree

Example Demo

// Create a Context Object
const InitContext = React.createContext()

class App extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (
            // Use a Provider to pass the current context to the following component tree
            <InitContext.Provider value='tadpole'>
                <Child />
            </InitContext.Provider>
        )
    }
}

function Child(props) {
    return (
            <LastComponent />
        )
}

class LastComponent extends React.Component {
    // Specify contextType to read the current context
    static contextType = InitContext
    render() {
        return (
            <div>name: {this.context}</div>
        )
    }
}

Notes for using Context:

  • Each Context object returns a Provider React component
  • The defaultValue parameter of a component takes effect only if it is in a tree that does not match a Provider, and the default value is undefined
  • Multiple providers can also be nested, and the underlying data Provider that covers the outer layer receives a value attribute and passes it to the consumer component (React looks up to the nearest Provider and uses its value)
  • Can be accessed in any life cycle, including render functions

More References Context API

Non-nested component communication

There are generally several ideas for communication between non-nested components:

  • Find a parent component common to the component (you can refer to this) Comment Component Both parent-child and sibling components communicate)
  • Communicate using the Context API to create a globally accessible value
  • Creating custom events with events

In general, the first way to find a common parent component may be at many levels, which is not very friendly. The second way is not very friendly for later maintenance or reusability of components, so let's try the custom event method.

Instance Demo

First, we need an events package

npm install events -S

Implement component communication by registering and triggering events

import { EventEmitter } from 'events'

const emitter = new EventEmitter()

// Component A
class ComponentA extends React.Component {
    constructor(props) {
        super(props)
        this.state = {msg: ''}
    }
    componentDidMount() {
        // Register events when components are mounted
        this.eventEmitter = emitter.addListener('outputValue', msg => {
            this.setState({msg})
        })
    }
    componentWillUnMount() {
        // Remove events before component destruction
        emitter.removeListener(this.eventEmitter)
    }
    render() {
        return (
            <div>
                //This is Component A
                <div>assembly B Data passed in:{ this.state.msg }</div>
            </div>
        )
    }
}

// Component B
class ComponentB extends React.Component {
    constructor(props) {
        super(props)
        this.state = {value: ''}
    }
    valueChange = data => {
        this.setState({
            value: data.target.value
        })
    }
    btnClick = () => {
        // Trigger Custom Event
        emitter.emit('outputValue', this.state.value)
    }
    render() {
        return (
            <div>
                //This is Component B
                <input value={this.state.value} onChange={this.valueChange}></input>
                <button onClick={this.btnClick}>Click on me to deliver the message</button>
            </div>
            
        )
    }
}

Postnote

These are the common ways of communicating between React components. In fact, during our practice, we must also find some ways to communicate with multiple component relationships. The key is to use the most appropriate way.

Of course, for some more complex component communication, we can also choose to use state management tools, such as flux, redux, etc. to make our component communication easier and better managed

Finally, interested little partners can click here For more front-end snippets, welcome to star

Topics: Javascript React Attribute npm