Table of Contents
Component communication
The parent component communicates with the child component
The child component communicates with the parent component
Home Web Front-end JS Tutorial Detailed explanation of the use of component communication in React

Detailed explanation of the use of component communication in React

May 24, 2018 pm 02:22 PM
react use Detailed explanation

This time I will bring you a detailed explanation of the use of component communication in React. What are the precautions when using component communication in React? Here are practical cases, let’s take a look.

Component communication

Here we only talk about the communication between the React component and the component itself. Component communication is mainly divided into three parts:

  • Parent component to Subcomponent communication: The parent component passes parameters to the subcomponent or the parent component calls the method of the subcomponent

  • The subcomponent communicates with the parent component: The subcomponent passes parameters to the parent component or the child component Methods of calling parent components

  • Communication between sibling components: passing parameters or calling each other between sibling components

It is recommended not to have too deep embedding Set of relationships

The parent component communicates with the child component

  • Parent: The method of calling the child component is mainly usedthis.refs.c1.changeChildren1

  • Parent: Passing parameters to child components mainly uses text={this.state.text}

  • Child: Definition method changeChildren1 is used by the parent component to call the

  • child: use the property this.props.text to get the parameters passed from the parent component

//父组件向子组件通信
//父组件
var ParentComponent1 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },
    //输入事件
    change: function(event){
        this.setState({text: event.target.value});
        //调用子组件的方法
        this.refs.c1.changeChildren1(event.target.value);
    },
    render: function(){
        return (
            <p>
                <p><label>父组件</label><input type="text" onChange={this.change}/></p>
                <ChildrenComponent1 ref="c1" text={this.state.text}/>
            </p>                        
        )
    }
}) 
//子组件
var ChildrenComponent1 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },
    //被父组件调用执行
    changeChildren1: function(text){
        this.setState({text: text});
    },
    render: function(){
        return (
            <p>
                <p>子组件-来自父组件的调用:{this.state.text}</p>
                <p>子组件-来自父组件的传参:{this.props.text}</p>
            </p>                        
        )
    }
})  
ReactDOM.render(<ParentComponent1/>, document.getElementById('p1'));
Copy after login

The child component communicates with the parent component

  • Parent: Define the method changeParent for the child component to call

  • Child: The main method of calling the parent component Usethis.props.change(event.target.value);

  • ##
//子组件向父组件通信
//父组件
var ParentComponent2 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },
    //被子组件调用执行
    changeParent: function(text){
        this.setState({text: text});
    },
    render: function(){
        return (
            <p>
                <p>父组件-来自子组件的调用:{this.state.text}</p>                     
                <ChildrenComponent2 change={this.changeParent}/>
            </p>                        
        )
    }
}) 
//子组件
var ChildrenComponent2 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },
    //输入事件
    change: function(event){
        //调用子组件的方法
        this.props.change(event.target.value);
    },
    render: function(){
        return (
            <p>
                <p><label>子组件</label><input type="text" onChange={this.change}/></p>
            </p>                        
        )
    }
})  
ReactDOM.render(<ParentComponent2/>, document.getElementById('p2'));
Copy after login
Sibling component communication

  • Method 1 : Communicate through a common parent component

Because the React component must have and only one top-level element, there must be a common parent element (component) between sibling components, so Brothers can communicate through a common parent element (component). The communication method can be achieved by combining the father-son and son-father introduced above.

//兄弟组间通信-通过共同的父组件通信
//父组件
var ParentComponent3 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },
    //被子组件2调用,向子组件1通信
    changeChildren1: function(text){
        //调用子组件1的方法
        this.refs.cp1.changeState(text);
    },
    //被子组件1调用,向子组件2通信
    changeChildren2: function(text){
        //调用子组件2的方法
        this.refs.cp2.changeState(text);
    },                
    render: function(){
        return (
            <p>
                <p>父组件-来自子组件的调用:{this.state.text}</p>                     
                <ChildrenComponent3_1 change={this.changeChildren2} ref="cp1"/>
                <ChildrenComponent3_2 change={this.changeChildren1} ref="cp2"/>
            </p>                        
        )
    }
}) 
//子组件1
var ChildrenComponent3_1 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },
    changeState: function(text){
        this.setState({text: text});
    },                  
    //输入事件
    change: function(event){
        //调用子组件的方法
        this.props.change(event.target.value);
    },
    render: function(){
        return (
            <p>
                <p><label>子组件1</label><input type="text" onChange={this.change}/></p>
                <p>来自子组件2的调用-{this.state.text}</p>
            </p>                        
        )
    }
})  
//子组件2
var ChildrenComponent3_2 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },              
    changeState: function(text){
        this.setState({text: text});
    },  
    //输入事件
    change: function(event){
        //调用子组件的方法
        this.props.change(event.target.value);
    },
    render: function(){
        return (
            <p>
                <p><label>子组件2</label><input type="text" onChange={this.change}/></p>
                <p>来自子组件1的调用-{this.state.text}</p>
            </p>                        
        )
    }
})              
ReactDOM.render(<ParentComponent3/>, document.getElementById('p3'));
Copy after login
Method 2: Communication through context

and through The common parent component communicates the same, the difference is that the context

//兄弟组间通信-通过 context 通信
//父组件
var ParentComponent4 = React.createClass({
    getChildContext: function(){
        return {
            changeChildren1: function(text){
                this.refs.cp1.changeState(text)
            }.bind(this),
            changeChildren2: function(text){
                this.refs.cp2.changeState(text)
            }.bind(this)
        }
    },
    childContextTypes: {
        changeChildren1: React.PropTypes.func.isRequired,
        changeChildren2: React.PropTypes.func.isRequired
    },                
    render: function(){
        return (
            <p>
                <ChildrenComponent4_1 ref="cp1"/>
                <ChildrenComponent4_2 ref="cp2"/>
            </p>                        
        )                    
    }
}) 
//子组件1
var ChildrenComponent4_1 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },
    contextTypes: {
        changeChildren2: React.PropTypes.func.isRequired
    },                         
    changeState: function(text){
        this.setState({text: text});
    },                  
    //输入事件
    change: function(event){
        //调用子组件的方法
        this.context.changeChildren2(event.target.value);
    },
    render: function(){
        return (
            <p>
                <p><label>子组件1</label><input type="text" onChange={this.change}/></p>
                <p>来自子组件2的调用-{this.state.text}</p>
            </p>                        
        )
    }
})  
//子组件2
var ChildrenComponent4_2 = React.createClass({
    getInitialState: function(){
        return {
            text: ''
        }
    },   
    contextTypes: {
        changeChildren1: React.PropTypes.func.isRequired
    },                            
    changeState: function(text){
        this.setState({text: text});
    },  
    //输入事件
    change: function(event){
        //调用子组件的方法
        this.context.changeChildren1(event.target.value);
        
    },
    render: function(){
        return (
            <p>
                <p><label>子组件2</label><input type="text" onChange={this.change}/></p>
                <p>来自子组件1的调用-{this.state.text}</p>
            </p>                        
        )
    }
});                
ReactDOM.render(<ParentComponent4/>, document.getElementById('p4'));
Copy after login
is called. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the implementation steps of PromiseA

Detailed explanation of the steps to highlight the selected li in react implementation

The above is the detailed content of Detailed explanation of the use of component communication in React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

How to use spaces correctly in Go How to use spaces correctly in Go Mar 29, 2024 pm 03:42 PM

Go language is a simple, efficient, and highly concurrency programming language. It is an open source language developed by Google. In the Go language, the use of spaces is very important, it can improve the readability and maintainability of the code. This article will introduce how to use spaces correctly in Go language and provide specific code examples. Why you need to use spaces correctly In the programming process, the use of spaces is very important for the readability and beauty of the code. Appropriate use of spaces can make code clearer and easier to read, thus reducing

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

The definition and use of full-width characters The definition and use of full-width characters Mar 25, 2024 pm 03:33 PM

What are full-width characters? In computer encoding systems, double-width characters are a character encoding method that takes up two standard character positions. Correspondingly, the character encoding method that occupies a standard character position is called a half-width character. Full-width characters are usually used for input, display and printing of Chinese, Japanese, Korean and other Asian characters. In Chinese input methods and text editing, the usage scenarios of full-width characters and half-width characters are different. Use of full-width characters Chinese input method: In the Chinese input method, full-width characters are usually used to input Chinese characters, such as Chinese characters, symbols, etc.

How to use Dewu installment purchase How to use Dewu installment purchase Mar 24, 2024 pm 01:46 PM

How to use Dewu installment purchase? You can use the installment payment service to purchase your favorite goods in Dewu APP. Most people don’t know how to use Dewu installment purchase. Next is the Dewu installment purchase brought by the editor to users. Graphic tutorial on how to use it. Interested users can come and take a look! Dewu usage tutorial How to use Dewu installment purchase 1. First open Dewu APP and enter the main page, select your favorite product and enter the purchase page; 2. Then on the product purchase page in the picture below, click [Buy Now] in the lower right corner; 3 , then select the appropriate code number and click the price on the left; 4. Then on the order confirmation page, select [Submit Order] in the lower right corner; 5. Finally, on the payment page, check the button behind [Huabei Installment]. Just select the installment type and you’re done

See all articles