0Pricing
TypeScript Academy · レッスン

Propsとchildren、イベントハンドラー、refs

型付きのpropsとchildrenを定義し、イベントハンドラーを安全に接続し、DOMノードにアクセスするためのrefsを作成・使用します

「Propsとchildren、イベントハンドラー、refs」はCoddyKit上の無料TypeScript Academyレッスンです。 これはレッスン1/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはTypeScript Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 TypeScript Academyコースには全3レッスンが含まれています。

導入

目標: 型付き React コンポーネントを構築します。props(children を含む)を定義し、イベントハンドラーに正確な型を付け、ref を使って input にフォーカスします。

  • 型付き props インターフェース
  • イベントハンドラーの型
  • DOM アクセスのための ref

型付き props

props インターフェースを宣言し、オプショナルな props を使って union のリテラルで絞り込みます。デフォルト値はコンポーネント内に置いてください。

import React from "react"

interface BadgeProps {
  text: string
  color?: "primary" | "success" | "warning"
}

export function Badge({ text, color = "primary" }: BadgeProps) {
  const bg = color === "success" ? "#16a34a" : color === "warning" ? "#d97706" : "#2563eb"
  return <span style={{ backgroundColor: bg, color: "white", padding: 4, borderRadius: 6 }}>{text}</span>
}

export default function App() {
  return (
    <div style={{ display: "grid", gap: 8 }}>
      <Badge text="Saved" color="success" />
      <Badge text="Warn" color="warning" />
    </div>
  )
}

children

PropsWithChildren<T>(または React.PropsWithChildren)を使うと、型付きの children スロットを props に追加できます。

import React, { PropsWithChildren } from "react"

type CardProps = PropsWithChildren<{ title: string }>

function Card({ title, children }: CardProps) {
  return (
    <div style={{ border: "1px solid #e5e7eb", padding: 12, borderRadius: 8 }}>
      <h3 style={{ margin: 0 }}>{title}</h3>
      <div>{children}</div>
    </div>
  )
}

export default function App() {
  return (
    <Card title="Dashboard">
      <p>Children are typed automatically.</p>
    </Card>
  )
}

イベントハンドラー

React.MouseEvent<Element> と React.ChangeEvent<HTMLInputElement> を優先してください。これらを使うと、型付きの target/currentTarget を利用できます。

import React from "react"

export default function App() {
  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    console.log("clicked", e.currentTarget.name)
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log("value", e.target.value)
  }

  return (
    <div style={{ display: "grid", gap: 8 }}>
      <input name="n" onChange={handleChange} placeholder="Type here" />
      <button name="ok" onClick={handleClick}>Confirm</button>
    </div>
  )
}

ref: DOM へのアクセス

useRef<HTMLInputElement>(null) により、null を取り得る ref を保持できます。オプショナルチェーンを使って DOM ノードに安全にアクセスしてください。

import React, { useRef } from "react"

export default function App() {
  const inputRef = useRef<HTMLInputElement>(null)

  const focusInput = () => {
    inputRef.current?.focus()
  }

  return (
    <div style={{ display: "grid", gap: 8 }}>
      <input ref={inputRef} placeholder="Focus me" />
      <button onClick={focusInput}>Focus</button>
    </div>
  )
}

ref の転送

forwardRef を使うと、親から子の DOM ノードにアクセスできます。正確な型付けのために要素型を指定してください。

import React, { forwardRef } from "react"

type TextInputProps = { label: string }

const TextInput = forwardRef<HTMLInputElement, TextInputProps>(function TextInput({ label }, ref) {
  return (
    <label style={{ display: "grid", gap: 4 }}>
      <span>{label}</span>
      <input ref={ref} />
    </label>
  )
})

export default function App() {
  const setRef = (el: HTMLInputElement | null) => { if (el) el.focus() }
  return <TextInput ref={setRef} label="Auto focus" />
}

イベントの型付けの確認

クイックチェック: ボタンのクリックハンドラーに対する正しい型はどれですか。

まとめ

まとめ: props(children を含む)を定義し、イベントに正確な型を付け、ref(forwardRef を含む)を使って DOM ノードに安全にアクセスします。

よくある質問

「Propsとchildren、イベントハンドラー、refs」レッスンは無料ですか?

はい。「Propsとchildren、イベントハンドラー、refs」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、TypeScript Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 TypeScript Academyコースには全3レッスンが含まれています。

「Propsとchildren、イベントハンドラー、refs」で何を学びますか?

型付きのpropsとchildrenを定義し、イベントハンドラーを安全に接続し、DOMノードにアクセスするためのrefsを作成・使用します ブラウザで直接実行するハンズオンコードでTypeScript Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

TypeScript Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのTypeScript Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/3です。

「Propsとchildren、イベントハンドラー、refs」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このTypeScript Academyレッスンでコードを書いて実行できますか?

はい。すべてのTypeScript Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Propsとchildren、イベントハンドラー、refs
  2. Stateとreducer、Contextの型付け
  3. コンポーネントのジェネリクス — 入門
← TypeScript Academyに戻る