読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
カードのボタンが押されたことを、親に知らせます。
type ProductCardProps = {
product: Product;
onAdd: (productId: string) => void;
};
export const ProductCard = ({ product, onAdd }: ProductCardProps) => {
return (
<article className="product-card">
<h3>{product.name}</h3>
<p>{product.price}円</p>
<button type="button" onClick={() => onAdd(product.id)}>
予約に加える
</button>
</article>
);
};
const handleAdd = (productId: string) => {
console.log(`${productId} が予約に加えられました`);
};
<ProductCard product={croissant} onAdd={handleAdd} />
props は親から子への一方通行です。子から親に何かを知らせるときは、親が関数を props で渡し、子がその関数を呼びます。
| 役割 | すること |
|---|---|
| 親 | 何が起きたときに何をするかを関数で決め、渡す |
| 子 | ボタンが押されたら、受け取った関数を呼ぶ |
関数を受け取る props の名前は、onAdd や onSelect のように on で始め、「何が起きたときか」を表します。渡す関数の名前は、handleAdd のように handle で始めることが多くあります。
type ReservationRowProps = { reservation: Reservation; onCancel: (reservationId: string) => void; }; と書きます。行の中のボタンには onClick={() => onCancel(reservation.id)} を付けます。
11 / 16