3
0

More than 1 year has passed since last update.

Reactでemitする方法

Posted at

はじめに

vueだと、$emitで親コンポーネントのイベントを発火します。
今回は、Reactで子コンポーネントのイベントを親コンポーネントに伝える方法を紹介したいと思います。

親コンポーネント

import React from 'react'
import Layout from '../components/Layout'
import { Button } from '@material-ui/core'
import ChildComponentDialog from 'src/components/diagnose/ChildComponentDialog'

const IndexPage = () => {
  const [open, setOpen] = React.useState(false)

  const openDialog = () => {
    setOpen(true)
  }
    // 子コンポーネントのイベントハンドラに渡す用の関数
  const closeDialog = () => {
    setOpen(false)
  }

  return (
    <div>
      <h1>診断アプリです。</h1>
      <div>
        <Button variant='outlined' onClick={openDialog}>
          診断する
        </Button>
      </div>
      <ChildComponentDialog open={open} onClose={closeDialog} /> // 子コンポーネント
    </div>
  )
}

export default IndexPage

子コンポーネント

import React from 'react'
import {
  Dialog,
  withMobileDialog,
  DialogTitle,
  makeStyles,
  DialogActions,
  Button,
} from '@material-ui/core'

type ChildComponentDialogProps = {
  open: boolean
  onClose: () => void
  onSubmit?: () => void
}
const ChildComponentDialog: React.FC<ChildComponentDialogProps> = props => {
  const { open, onClose, onSubmit } = props
  return (
    <BasicDialog
      open={open}
      // 親コンポーネントからpropsで渡された関数
      onClose={onClose}
      onSubmit={onSubmit}
      title='診断コンテンツ'
    >
      <div/>
    </BasicDialog>
  )
}

export default ChildComponentDialog

親コンポーネントから子コンポーネントにpropsで子コンポーネントのイベントハンドラに受け渡すことで、イベントが発火したタイミングで親イベントを発火することができます。

イベントハンドラ
https://ja.reactjs.org/docs/handling-events.html

ちなみに、子コンポーネントのデータをemitを通して親コンポーネントに渡すこともできます。

親コンポーネントのイベント用の関数

const openDialog = (args) => {
  setOpen(args)
}

親コンポーネント

const ChildComponentDialog: React.FC<ChildComponentDialogProps> = props => {
  const { open, onClose, onSubmit } = props
  return (
    <BasicDialog
      open={open}
      onClose={onClose}
      // 引数を指定
      onSubmit={() => onSubmit(true)}
      title='診断コンテンツ'
    >
      <div/>
    </BasicDialog>
  )
}

export default ChildComponentDialog

() => onSubmit(true)

引数を渡すことが可能です。ちなみに、onSubmit(true)だと動かないです。

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