0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React 子コンポーネントのChildrenから親コンポーネントに変数を返す 備忘録

Last updated at Posted at 2022-10-17

Reactを触っていて、基本的には子から親に値を返す場合Propsの中からSetterの様な関数を子を呼び出す時にセットするしかないなと思ってましたけど
別の方法もあったので忘れないように記事に起こします。

今までこれしか無いと思ってたやり方

const ParentComp = () => {
    const [state, setState] = useState('');
    return <>
        <ChildComp setter={setState} />
        <div>{state}</div>
    </>
}
// ------------------------------
const ChildComp = (props)=>{
    return <input onChange={(e)=>props.setter(e.target.value)}>
}

Childrenを介して値を返すやり方

const ParentComp = () => {
    return <ChildComp>
        {(test)=>{
            <div>{test}</div>
        }}
    </ChildComp>
}

// ------------------------------
type Props = {
  children(test: any): React.ReactElement<HTMLElement>;
};
const ChildComp: React.FC<Props> = (props) => {
  const testObj = { test: 'test' };
  return <>{props.children(testObj)}</>;
};

下のやり方だと何かWrapperのようにChildrenをまとめ上げて、Wrapperの中のロジックで出た変数などをChildrenに入れたい時なんかは利用できると思います。

このやり方の名称みたいなのがあれば有識者の方、教えていただけたらと思います。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?