ทั้งสองอย่างเก็บข้อมูลที่ส่งผลต่อสิ่งที่ component render ออกมา แต่พวกมันแตกต่างกันใน ใครเป็นเจ้าของข้อมูล และ ว่าสามารถเปลี่ยนแปลงได้หรือไม่
ทั้งสองอย่างเก็บข้อมูลที่ส่งผลต่อสิ่งที่ component render ออกมา แต่พวกมันแตกต่างกันใน ใครเป็นเจ้าของข้อมูล และ ว่าสามารถเปลี่ยนแปลงได้หรือไม่
// `step` is a PROP — given by the parent, the child only reads it.
// `count` is STATE — owned here, changes on click, causes a re-render.
function Counter({ step }) {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + step)}>
{count}
</button>
);
}
// Parent decides the step and passes it down:
<Counter step={5} />
ข้อมูลไหลลง (parent → child ผ่าน props) และการเปลี่ยนแปลงไหลขึ้น (child ขอให้ parent เปลี่ยนแปลงสิ่งต่าง ๆ ผ่าน callback prop เช่น onChange) การไหลทางเดียวนี้คือสิ่งที่ทำให้ React apps สามารถคาดเดาได้
props.x = 1) เป็นข้อบกพร่อง — React จะไม่ re-render และคุณได้หักเหเจ้าของของ parent เรียก callback ที่ parent ให้คุณมาเพื่อให้ parent อัปเดต state ของมันเองและส่งค่าใหม่ลงคลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค