Components ကြား State မျှဝေခြင်း
19.3
မျှဝေသုံးမယ့် state ကို components နှစ်ခုရဲ့ အနီးဆုံး common parent မှာ ထားပါ။ Values နဲ့ event handlers ကို children ဆီ props နဲ့ ပို့ပါ။
Code စမ်းလို့ရတဲ့ သင်ခန်းစာ ဖွင့်ရန်
ဒီစာမျက်နှာမှာ
Value တစ်ခုစီအတွက် Owner တစ်ခုထားခြင်း
Selection တူတူ ပြတဲ့ components တွေက state တစ်ခုတည်း ဖတ်သင့်ပါတယ်။ Child တစ်ခုစီမှာ မိတ္တူသိမ်းရင် တန်ဖိုးတွေ ကွဲသွားနိုင်ပါတယ်။ ရွေးထားတဲ့ ID ကို parent မှာထားပြီး render ချိန်မှာ item ကို ရှာပါ။
import { useState } from "react";
function Choice({ label, selected, onChoose }) {
return <button aria-pressed={selected} onClick={onChoose}>{label}</button>;
}
export default function ProductPicker() {
const [product, setProduct] = useState("pen");
return (
<>
<Choice label="Pen" selected={product === "pen"} onChoose={() => setProduct("pen")} />
<Choice label="Notebook" selected={product === "notebook"} onChoose={() => setProduct("notebook")} />
<p>Selected: {product}</p>
</>
);
}
Child Components ပြန်သုံးလို့ရအောင် ထားခြင်း
Controlled child က လက်ရှိ value ကို props ကနေ ယူပြီး ပြောင်းစေချင်ရင် callback နဲ့ parent ကို အသိပေးပါတယ်။ Child တစ်ခုတည်း လိုအပ်တဲ့ အချက်တွေ အတွက် local state သုံးနိုင်ပါတယ်။
import { useState } from "react";
function QuantityInput({ value, onChange }) {
return (
<label>
Quantity
<input type="number" min="1" value={value}
onChange={event => onChange(event.target.value)} />
</label>
);
}
export default function OrderForm() {
const [quantity, setQuantity] = useState("1");
return <QuantityInput value={quantity} onChange={setQuantity} />;
}