In React, Function Components are a way to define components. They are essentially JavaScript functions that can accept props (properties) as parameters and return React elements. These props allow you to pass data from parent component to child component.
Pass Props
When you want to pass data from a parent component to a child component, you can pass this data through the properties of the component tag (i.e. elements in JSX). In subcomponents, you can receive this data through the function's parameters, which are named as conventionprops
(Although you can use any valid variable name).
Parent component
import React from 'react'; import ChildComponent from './ChildComponent'; function ParentComponent() { return ( <div> <h1>I'm the parent component</h1> {/* Pass data to subcomponents */} <ChildComponent message="Hello from Parent!" /> </div> ); } export default ParentComponent;
Subcomponents
import React from 'react'; function ChildComponent(props) { // Use to access passed data return ( <div> <h2>I'm a child component</h2> <p>{}</p> </div> ); } export default ChildComponent;
Simplify Props with deconstructed assignment
If you only need to access a few specific properties from props, you can use ES6's deconstructed assignment syntax to simplify the code.
function ChildComponent({ message }) { // Use message variable directly without passing return ( <div> <h2>I'm a child component</h2> <p>{message}</p> </div> ); }
Transfer functions as Props
In addition to basic data types and objects, you can also pass functions as props to child components. This allows the child component to call these functions when needed, thereby communicating with the parent component (e.g. triggering event processing).
Parent component
function ParentComponent() { const handleMessage = (msg) => { (msg); }; return ( <div> <ChildComponent handleMessage={handleMessage} /> </div> ); }
Subcomponents
function ChildComponent({ handleMessage }) { return ( <button onClick={() => handleMessage('Hello from Child!')}> Click me </button> ); }
In this way, React's function components provide a flexible and powerful way to pass data and functions between components, thereby enabling communication and interaction between components.
This is the end of this article about the implementation of parameters transfer of React function components. For more related contents of parameters transfer of React function components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!