LoginSignup
1
0

More than 1 year has passed since last update.

React + TypeScript – 子コンポーネントから親コンポーネントの関数を実行する

Posted at

コード

Parent.tsx

親コンポーネントでは子コンポーネントにpropsとして使う引数(?)を渡す

import { useState, useEffect } from 'react'

import Child from "./Child";

function Example() {
  const [task, setTask] = useState("");

  const handleClick = () => {
    setTask("task");
  };

  return (
    <div>
      <Child handleClick={handleClick}/>
      <div>
        {task}
      </div>
    </div>
  );
}

export default Example;

Child.tsx

子コンポーネントではprops経由で関数を実行する

function Child(props: any) {
  return (
    <div>
      <button onClick={props.handleClick}>Click</button>
    </div>
  );
}

export default Child;

環境

react@18.2.0

表示例

image

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
0
0

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
1
0