Home Backend Development PHP Tutorial Examples of communication between React components

Examples of communication between React components

Jun 28, 2017 pm 03:39 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 some text in component 1 and display it 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


and then in the parent The in the component is changed to


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


## Then we enter the In the component, bind the attached onShow attribute 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 content of the message in the parent layer state to make the content of the bound display layer change accordingly.


Promote the state (data) of the input layer to the parent component. Below It 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: there is no onInp() and content. ?Don’t worry, continue reading


Then rewrite the input layer subcomponent 1 in the parent 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 entire content of this article, I hope it will be helpful to everyone The learning is helpful, and I hope everyone will support Script Home.

The above is the detailed content of Examples of 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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

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

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.

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

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

See all articles