Call parent's function from a child component React js

 https://www.learnbestcoding.com/post/72/call-parent-function-from-child-component-react

To call a parent's function from a child component, pass the function reference to the child component as a prop. Then you can call that parent's function from the child component like props.parentMethodName().

In the example code, we create a parent component named Parent. The Parent component has the method parentFunction that we intend to call from the child component. The parentFunction() accepts a number as an argument and updates the count state variable by calling the setCount method.

Note that we pass the parentFunction() to the child component as a prop. <Child parentFunction={parentFunction}/>

import { useState } from "react"
import Child from "./components/Contact"
export const Parent = () => {
const [count, setCount] = useState<number>()

const parentFunction = (points: number) => {
  setCount(points)
}
return(
    <div>
	<div>
	   <h2>Parent Component</h2><br/>
	   {count && `Received: ${count} points from child`}
	   <Child parentFunction={parentFunction}/>
	</div>
    </div>
 )
}
export default Parent
Calling parents function from child component
Figure 1: Calling parents function from child component

The child component receives the parent's method parentFunction() as a prop. Then we call the parent function with props.parentFunction(points) which executes the parent's function and updates the count state variable.

import { useState } from "react"

interface ChildProps {
  parentFunction: Function
}

const Child = (props: ChildProps) => {
 const [points, setPoints] = useState<number>()
  return(
    <div style={{padding: 30}}>
      <div>
        <h3>Child Component</h3>
        <p>Send : <input value={points} onChange={(e) => setPoints(+e.target.value)}/> points to Parent</p>
        <p style={{textAlign: "center"}}><button onClick={() => props.parentFunction(points)}>Send to parent</button></p>
      </div>
  </div>
  )
 }
 export default Child

Không có nhận xét nào:

StaticImage

  import React , { useEffect , useRef } from "react" import { StaticImage } from "gatsby-plugin-image" impor...