兄弟コンポーネント間の値の受け渡し

cpoint-lab.co.jp

 

A⇒B⇒Zへ値を渡す

 

<index.js>

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Parent from './Parent';
import reportWebVitals from './reportWebVitals';
import { unstable_batchedUpdates } from 'react-dom' // or 'react-native'


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Parent />
  </React.StrictMode>
);

// If you want to start measuring performance in your Parent, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

<Parent.js>

import {useState} from 'react';
import ChildComponentA from './ChildComponentA';
import ChildComponentB from './ChildComponentB';
import ChildComponentZ from './ChildComponentZ';

const Parent = ()=>{
    const [val,setVal] = useState('');
    const [valval,setValval] = useState(val);
    return(
        <div>
            <ChildComponentA emitVal={setVal}/>
            <ChildComponentB val = {val}
                             emitValval={setValval}/>
            <ChildComponentZ valval = {valval}/>
        </div>
    );
}

export default Parent;

 

<ChildComponentA.js>

const ChildComponentA = (props)=>{
    return(
        <div>
            <button type="button"
                    onClick={()=>props.emitVal(Math.random())}>
                        ランダムに値を親コンポーネントに送信
            </button>
        </div>
    );
}

export default ChildComponentA;

 

<ChildComponentB.js>

const ChildComponentB = (props)=>{
    return(
        <div>
           <p>受け取った値:{props.val}</p>
           <button type="button"
                    onClick={()=>props.emitValval(props.val)}>
                        値を受け渡す
            </button>
        </div>

    );
}

export default ChildComponentB;

 

<ChildComponentZ.js>

const ChildComponentZ = (props)=>{
    return(
        <div>
           <p>受け取った値:{props.valval}</p>
        </div>

    );
}

export default ChildComponentZ;