How can child components pass values to parent components in React? Reactの子コンポーネントが親コンポーネントに値を伝達する方法は何ですか?

Reactの場合、子コンポーネントから親コンポーネントに値を渡す方法は2つあります。

  1. callback関数を使うことで、親コンポーネントはpropsを介してコールバック関数を子コンポーネントに渡すことができ、子コンポーネントはこのコールバック関数を呼び出して引数を渡すことで値を親コンポーネントに伝えることができます。

親コンポーネントのサンプルコード:

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

function ParentComponent() {
  const [value, setValue] = useState('');

  const handleChildValue = (childValue) => {
    setValue(childValue);
  };

  return (
    <div>
      <ChildComponent onValueChange={handleChildValue} />
      <p>Value from child component: {value}</p>
    </div>
  );
}

export default ParentComponent;

サブコンポーネントのサンプルコード:

import React, { useState } from 'react';

function ChildComponent({ onValueChange }) {
  const [inputValue, setInputValue] = useState('');

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

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

export default ChildComponent;

上の例では、子コンポーネントChildComponentはonValueChangeという名前のpropsを受け取ります。これはコールバック関数です。子コンポーネントの入力ボックスの値が変更されると、handleChange関数が呼び出され、入力された値がonValueChangeコールバック関数に渡され、親コンポーネントに値が渡されます。

  1. 親コンポーネントは、Contextを作成し、必要な値をContextのProviderに配置することで、子コンポーネントはその値を取得するためにContextのConsumerを使用することができます。

親コンポーネントのサンプルコード:

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

function ParentComponent() {
  const [value, setValue] = useState('');

  return (
    <div>
      <MyContext.Provider value={value}>
        <ChildComponent />
      </MyContext.Provider>
      <p>Value from child component: {value}</p>
    </div>
  );
}

export default ParentComponent;

サブコンポーネントのサンプルコード:

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

function ChildComponent() {
  const value = useContext(MyContext);
  const [inputValue, setInputValue] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <div>
      <input type="text" value={inputValue} onChange={handleChange} />
      <p>Value from parent component: {value}</p>
    </div>
  );
}

export default ChildComponent;

上記の例では、親コンポーネントParentComponentがMyContextを作成し、そのvalueをMyContext.Providerのvalueプロパティに設定しました。 子コンポーネントChildComponentは、useContextを使用してMyContextの値を取得し、それをページに表示します。 子コンポーネントはまた、inputのonChangeイベントを使用してinputValueの状態値を更新できますが、この値は子コンポーネント内にのみ存在し、親コンポーネントには伝わりません。

bannerAds