search
HomeBackend DevelopmentPHP TutorialExamples of communication between React components

Examples of communication between React components

Jun 28, 2017 pm 03:39 PM
reactExamplecommunication

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>
   }

  }


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>
    );
   }
  }


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;
   }


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


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


## 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>
  }


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}/>
  }
 }


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}/>

); } }


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') );


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
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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function