Home Web Front-end JS Tutorial Example tutorial on communication between React components

Example tutorial on communication between React components

Jun 28, 2017 pm 01:29 PM
react Example communication

This article mainly introduces the example code of communication between React components. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Recently, I have just started to learn the UI framework of react.js. The biggest feeling that the react library gives me is that it can completely take over the UI layer. When you want to change something in the view, you only need to change the state in this.state. I still like that as long as the things in the data layerView layer are manipulated, they will change. You can get rid of the direct operation of the DOM. After all, it would be more complicated to do it directly. It should be string mixed with various css in the logic layer js, which is a bit uncomfortable for me (this tag is also mixed in JSX , but I think it should not be regarded as a label, but as a statement (you will get used to it).

Go back to the focus of the past few days and talk about state transfer between react components.

Above code:

1. Define two sub-components child-1 and child-2


 //child-1 子组件-1为输入框
  class Input extends React.Component{
   constructor(...args){
   super(...args);
   }
   render(){
    return <input type="text"/>
   }
  }
  //child-2  子组-2为显示框
  class Show extends React.Component{
   constructor(...args){
    super(...args);
   }
   render(){
    return <p></p>
   }

  }
Copy after login

2. Define the parent component Parent and insert the two child components into the parent component


class Parent extends React.Component{
   constructor(...args){
    super(...args);
   }
   render(){
    return(
     <p>
      <Input}/>
      <Show/>
     </p>
    );
   }
  }
Copy after login

The current task is to input the total in component 1 Some text is displayed in component 2 at the same time.

Analysis: To synchronize component 2 with component 1, let both components 1 and 2 bind the state of the parent component. That means keeping both components under control. The direction of data is that component 1 promotes its own data to the parent layer and saves it in the state of the parent layer. The data in the parent layer is passed to component 2 through propsproperty in component 2 and bound in the view layer.

The first step is to bind the component


//在父层中的constructor中定义状态为一个空的message,this.state = {message:&#39;&#39;}
class Parent extends React.Component{
  constructor(...args){
   super(...args);
   this.state = {
    message:&#39;&#39;
   }
Copy after login

Then in the parent component Change to


<Show onShow={this.state.message}/>
Copy after login

Then we enter the component and bind the onShow attribute of this component to its content. The component becomes


class Show extends React.Component{
  constructor(...args){
   super(...args);
  }
  render(){
   return <p>{this.props.onShow}</p>
  }
Copy after login

In this way, the data of the display layer of component 2 has been bound. Next, we only need to change the status of the parent layer. The content of the message can make the content of the bound display layer change accordingly

Promote the status (data) of the input layer to the parent component. The following is the rewritten component 1


class Input extends React.Component{
  constructor(...args){
    super(...args);
  }
   //将输入的内容更新到自身组件的状态中,并且将改变后的状态作为参数传递给该组件的一个自定义属性onInp()
  fn(ev){ 
   this.props.onInp(ev.target.value);
  }
  render(){
   //用onInput(注意react中采用驼峰写法和原生的略有不同)绑定fn()函数
   return <input type="text" onInput={this.fn.bind(this)} value={this.props.content}/>
  }
 }
Copy after login

There may be a problem when you see this: onInp() and content are not there? Don’t worry, continue reading

then rewrite the parent Input layer sub-component 1 in the component,


class Parent extends React.Component{
  constructor(...args){
   super(...args);
   this.state = {
    message:''
   };
  }
  //传进的text是其提升上来的状态,然后再更新父组件的状态
  fn(text){
   this.setState({
    message:text
   })
  }
  render(){
   return(
    

/* onInp就出现在这里,并绑定一个函数, 并且有一个content将父组件的状态同步到子组件中 */ <Show onShow={this.state.message}/>

); } }
Copy after login

The finished code is like this


// 父组
 class Parent extends React.Component{
  constructor(...args){
   super(...args);
   this.state = {
    message:''
   };
  }
  onInp(text){
   this.setState({
    message:text
   })
  }
  render(){
   return(
    

<Show onShow={this.state.message}/>

); } } //child-1 class Input extends React.Component{ constructor(...args){ super(...args); } fn(ev){ this.props.onInp(ev.target.value); } render(){ return } } //child-2 class Show extends React.Component{ constructor(...args){ super(...args); } render(){ return <p>{this.props.onShow}</p> } } //最后渲染出 ReactDOM.render( , document.getElementById('app') );
Copy after login

The above is the detailed content of Example tutorial on communication between React components. 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)

New generation of optical fiber broadband technology - 50G PON New generation of optical fiber broadband technology - 50G PON Apr 20, 2024 pm 09:22 PM

In the previous article (link), Xiao Zaojun introduced the development history of broadband technology from ISDN, xDSL to 10GPON. Today, let’s talk about the upcoming new generation of optical fiber broadband technology-50GPON. █F5G and F5G-A Before introducing 50GPON, let’s talk about F5G and F5G-A. In February 2020, ETSI (European Telecommunications Standards Institute) promoted a fixed communication network technology system based on 10GPON+FTTR, Wi-Fi6, 200G optical transmission/aggregation, OXC and other technologies, and named it F5G. That is, the fifth generation fixed network communication technology (The5thgenerationFixednetworks). F5G is a fixed network

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

The development history of wireless mice The development history of wireless mice Jun 12, 2024 pm 08:52 PM

Original title: "How does a wireless mouse become wireless?" 》Wireless mice have gradually become a standard feature of today’s office computers. From now on, we no longer have to drag long cords around. But, how does a wireless mouse work? Today we will learn about the development history of the No.1 wireless mouse. Did you know that the wireless mouse is now 40 years old? In 1984, Logitech developed the world's first wireless mouse, but this wireless mouse used infrared as a The signal carrier is said to look like the picture below, but later failed due to performance reasons. It was not until ten years later in 1994 that Logitech finally successfully developed a wireless mouse that works at 27MHz. This 27MHz frequency also became the wireless mouse for a long time.

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.

A brief history of broadband Internet technology A brief history of broadband Internet technology Apr 16, 2024 am 09:00 AM

In today's digital age, broadband has become a necessity for each of us and every family. Without it, we would be restless and restless. So, do you know the technical principles behind broadband? From the earliest 56k "cat" dial-up to the current Gigabit cities and Gigabit homes, what kind of changes has our broadband technology experienced? In today’s article, let’s take a closer look at the “Broadband Story”. Have you seen this interface between █xDSL and ISDN? I believe that many friends born in the 70s and 80s must have seen it and are very familiar with it. That's right, this was the interface for "dial-up" when we first came into contact with the Internet. That was more than 20 years ago, when Xiao Zaojun was still in college. In order to surf the Internet, I

Methods and techniques for implementing Socket communication in PHP Methods and techniques for implementing Socket communication in PHP Mar 07, 2024 pm 02:06 PM

PHP is a commonly used development language that can be used to develop various web applications. In addition to common HTTP requests and responses, PHP also supports network communication through Sockets to achieve more flexible and efficient data interaction. This article will introduce the methods and techniques of how to implement Socket communication in PHP, and attach specific code examples. What is Socket Communication Socket is a method of communication in a network that can transfer data between different computers. by S

The main peak of Changbai Mountain can access the Internet normally: Jilin Mobile and ZTE completed 2.6G + 700M three-carrier aggregation for commercial use, with a peak rate of more than 2.53Gbps The main peak of Changbai Mountain can access the Internet normally: Jilin Mobile and ZTE completed 2.6G + 700M three-carrier aggregation for commercial use, with a peak rate of more than 2.53Gbps Jul 25, 2024 pm 01:20 PM

According to news on July 25, Jilin Mobile and ZTE have completed commercial use of three-carrier aggregation based on the 2.6G frequency band (100+60M) and the 700M frequency band (30M) on the main peak of Changbai Mountain. The peak rate in field testing can reach more than 2.53Gbps. Officials pointed out that Changbai Mountain is one of the top ten famous mountains in China. It is now a national AAAAA tourist attraction, a world geological park, a world biosphere reserve, and the world's best nature reserve. The number of tourists received in 2023 will reach 2.7477 million, and 3CC will be deployed this time. It will greatly meet users’ network needs. According to reports, Jilin Mobile has taken the lead in completing the carrier aggregation pilot of a three-carrier network in the 2.6G (100+60M) plus 4.9G (100M) frequency band in early 2024, with peak downloads

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

See all articles