How can a parent component in React access the value of a child component?

In React, a parent component can pass values to a child component through props and retrieve values from the child component through a callback function.

Here is an example:

Parent component:

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const [childValue, setChildValue] = useState('');

  const handleChildValueChange = (value) => {
    setChildValue(value);
  };

  return (
    <div>
      <ChildComponent onValueChange={handleChildValueChange} />
      <p>子组件的值:{childValue}</p>
    </div>
  );
}

export default ParentComponent;

Child component:

import React, { useState } from 'react';

function ChildComponent({ onValueChange }) {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    const newValue = event.target.value;
    setValue(newValue);
    onValueChange(newValue);
  };

  return (
    <input type="text" value={value} onChange={handleChange} />
  );
}

export default ChildComponent;

In the parent component, a state variable childValue is created using the useState hook to store the value of the child component.

Next, create a callback function called handleChildValueChange that will be invoked when the value of the child component changes, and update the new value to the childValue variable.

In the child component, a state variable called value is created using the useState hook to store the value of the input box.

Next, create a handleChange function that will be called when the value of the input box changes, updating the new value into the value variable.

At the same time, call the onValueChange callback function passed down from the parent component and pass the new value as a parameter back to the parent component.

Finally, in the parent component, the functionality of the parent component getting the value from the child component is achieved by passing the handleChildValueChange function to the onValueChange attribute of the child component.

When the input field in the child component changes, the parent component will automatically update and display the newest value.

bannerAds