SoFunction
Updated on 2025-04-07

Do you know how to pass parameters of React components?

Preface

As we all know, in business development, no matter what framework is used, the following are the first things to be familiar with:

  • Project construction, basic configuration, naming specifications.
  • Routing configuration, configuring routing rules, etc.
  • Component communication, component specifications, etc.

What we are going to explore today are several ways of component communication in React, as well as their respective application scenarios.

Parent-child component communication

In React, the parent component can passpropsPass data and callback functions to subcomponents to implementCommunication between parent-child components. At the same time, the child components can be calledCallback function passed by the parent componentComePassing data to the parent componentOr trigger the behavior of the parent component, there are several points to note.

  • Props parameters are passed, and the incoming data is read-only.
  • Functional components can be directly deconstructed, and class components need to be passed.
  • When the child component data is passed to the parent component, the return value of the callback function is the passed parameter.
// 
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
​
function ParentComponent() {
  const [messageFromChild, setMessageFromChild] = useState('');
​
  const handleMessageFromChild = (message) => {
    setMessageFromChild(message);
  };
​
  return (
    <div>
      <h1>Parent Component</h1>
      <p>Message from Child: {messageFromChild}</p>
      <ChildComponent giveChildren={parentData} onMessage={handleMessageFromChild} />
    </div>
  );
}
​
export default ParentComponent;
// 
​
//1. Functional Components​
import React from 'react';
​
function ChildComponent(props) {
  const { onMessage , parentData } = props;
  const sendMessageToParent = () =&gt; {
    onMessage('Hello from Child!');
  };
​
  return (
    &lt;div&gt;
      &lt;h2&gt;Child Component&lt;/h2&gt;
      &lt;h2&gt;{ parentData }&lt;/h2&gt;
      &lt;button onClick={sendMessageToParent}&gt;Send Message to Parent&lt;/button&gt;
    &lt;/div&gt;
  );
}
​
export default ChildComponent;
​
//1. Class components​
import React, { Component } from 'react'
​
export default class ChildComponent extends Component {
    render() {
        return (
            &lt;div&gt;
                {}
            &lt;/div&gt;
        )
    }
}

Summary: Let's look at the above code. By deconstructing the property from props in the component's attribute name and in the child component, this property can also be a callback function. When the callback function is called, the entry parameter will be obtained from the formal parameters of the parent component, the same as the principle of jsonp.

Parent-sun component communication

Smart students believe that they can learn from one example through parent-child component communication, but for a transfer parameter and write several layers of callbacks, this kind of code does not seem to be applicable, so in order to solve this problem, react provides us with a method.createContextThis is a function that creates a React context, which provides a method to share values ​​in the component, and is passed layer by layer through props without display.

//Cross-component communicationimport React, { Component } from 'react'
//Create context to initial valueconst UserMessage = ({
    nickName: 'yyy',
    level: 1
})
​
export default class TextSingal extends Component {
    constructor(props) {
        super(props)
         = {
            nickName: 'kkk',
            level: 99,
            name: 'ppp',
            age: 9999
        }
    }
    render() {
        const { name, age } = 
        return (
            &lt;div&gt;
                &lt;h2&gt;Grandpa Components&lt;/h2&gt;
                &lt;h3&gt;name:{name}&lt;/h3&gt;
                &lt;h3&gt;age:{age}&lt;/h3&gt;
                {/* Change data Sun component also updates */}
                &lt;button onClick={() =&gt; ()}&gt;updated&lt;/button&gt;
                {/* Pass in state object and foo callback function */}
                {/* foo function is used for communication between Sun component and Ye component */}
                &lt; value={{ ..., foo: (name, age) =&gt; (name, age) }}&gt;
                    &lt;Father /&gt;
                &lt;/&gt;
​
            &lt;/div&gt;
        )
    }
    handelClick() {
        ({
            nickName: 'Tiger Power God',
            level: 9999
        })
    }
    updateDatas(name, age) {
        ({
            name,
            age
        })
    }
}
​
class Father extends Component {
    render() {
        return (
            &lt;div&gt;
                &lt;h2&gt;Dad Components&lt;/h2&gt;
                &lt;Son /&gt;
            &lt;/div&gt;
        )
    }
}
class Son extends Component {
    render() {
        // Deconstruction        const { nickName, level, foo } = 
        return (
            &lt;div&gt;
                &lt;h2&gt;Son component&lt;/h2&gt;
                &lt;h3&gt;nickname:{nickName}&lt;/h3&gt;
                &lt;h3&gt;level:{level}&lt;/h3&gt;
                {/* Both of the following calling methods are OK */}
                {/* Change the data of the Ye component */}
                &lt;button onClick={() =&gt; ()}&gt;updated&lt;/button&gt;
                &lt;button onClick={() =&gt; foo('Niu Batian', 18)}&gt;updated&lt;/button&gt;
            &lt;/div&gt;
        )
    }
    handelClick() {
        ('Niu Batian', 18)
    }
}
// Accept the value passed by the old component = UserMessage

Summary: Through the above we create a context and then useWhen the component is wrapped, the wrapped component will share this context, define a callback on the context, and callbacks can be called by the grand component, or use incoming data.

Brother Component Communication

Compared with the parameters passed by brother components in Vue, react will be relatively original. In Vue, parameters can be easily passed in various components through evenbus. The method of react is to create a common state in the parent component common to the brother component, and then the brother A component changes this state by passing the parameter to the parent component, and the parent component also passes the new value to the B component to achieve the purpose of the brother component passing the parameter.

Parent component

// Parent componentimport React, {Component} from "react"
import Abrother from './Abrother'
import Bbrother from './Bbrother'
​
export default class common extends Component {
    // Public component parts    state = {
        inputValue:''
    }
​
    handleUpdate = (inputValue) =&gt; {
        ({
            inputValue
        })
    }
​
    render(){
        return(
            &lt;&gt;
              &lt;Abrother sendFn={}/&gt;
              &lt;Bbrother sendValue={}/&gt;
            &lt;/&gt;
        )
    }
}

Brother A

import React,{Component} from "react";
​
export default class Abrother extends Component {
​
    // Brother component A needs to pass the value to a public parent component first    state = {
        inputValue:''
    }
​
    handleChange = (e)=&gt;{
        ();
        ({
            inputValue:
        })
    }
    handleSend = () =&gt; {
        const {sendFn} = ;
        sendFn()
    }
​
    render(){
        return(
            &lt;&gt;
               &lt;div&gt;
                   &lt;span&gt;AComponents&lt;/span&gt;
                   &lt;input type='text' value={} onChange={}&gt;&lt;/input&gt;
                   &lt;button onClick={}&gt;sendAComponents的值&lt;/button&gt;
               &lt;/div&gt;
            &lt;/&gt;
        )
    }
}

Brother B

import React, {Component} from "react"
​
export default class Bbrother  extends Component {
​
​
    render(){
        const { sendValue} = ;
        return (
            &lt;div&gt;
                &lt;span&gt;bComponents&lt;/span&gt;
                &lt;h1&gt;{ sendValue }&lt;/h1&gt;
            &lt;/div&gt;
        )
    }
}

Summary: Component A, if you want to pass the value in the input box to component B, first define a variable in the state of the parent component. This variable is to pass it to the value in component B. The parent component passes this value into component b in the form of props. Next, define the callback function trigger in the parent component and component A. When component A is data moved, callback function is called and the value in the parent component state is changed to achieve the purpose of passing the new value to component B.

Cross-component communication

props , when the components are coherent and shallow, you can directly use props to communicate.

context API, when component data spans hierarchy, you can use this method to save layers of props.

Event bus, evenbus, etc. Communication is carried out by introducing a library or writing a simple one by yourself.

useRedux MobX, For data processing of shared state in very complex components, these two libraries can be used for processing

Use Refs to manipulate DOM elements or component instances directly.

This is the article about the method of transferring parameters of React components. For more related contents of transferring parameters of React components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!