Rendering
#HelloFrontend #HelloErmine #HelloWorld2021
Rendering คืออะไร ?
คือ การนำ React element ที่เราสร้างไปแสดงผลในเบราว์เซอร์ด้วยการใช้ ReactDOM
import { ReactDOM } from 'react';
function Hello(props) {
return <h1>Hello {props.name}</h1>;
}
const element = <Hello name="Poopoo" />; // <h1>Hello Poopoo</h1>
const rootElement = document.getElementById("root");
ReactDOM.render(element, rootElement);elementคือ React element ที่เราจะนำไปแสดงผลrootElementคือ HTML element ที่เราเลือกเอง จะเป็นเหมือน container ที่ยอมให้ ReactDOM จัดการทุกอย่างที่อยู่ภายใน และใช้แสดงผลelement
Re-rendering
จะเกิดเมื่อ React element ที่ถูก render ไปแล้วมี props หรือ state ที่เปลี่ยนไปจาก render ครั้งก่อน
React element นั้น ๆ จะถูก render อีกรอบด้วยค่า props และ state ชุดใหม่
อัปเดต DOM แค่ส่วนที่เปลี่ยนไปเท่านั้น
ตัวอย่าง
สมมติให้ component A รับ prop ชื่อ name มาใช้เป็น
classNameในdiv
ถ้า render ครั้งแรกได้รับ
props.nameมาเป็นhello
แล้ว render ครั้งถัดไปได้รับ
props.nameมาเป็นhi
React จะเปรียบเทียบทั้งสอง render แล้วรู้ได้เองว่ามีแค่ className ของ div ที่เปลี่ยนไป จึงอัปเดตแค่ส่วนนั้นภายใน DOM โดยไม่ต้องสร้าง div ใหม่อีกรอบ
แหล่งอ้างอิง
Last updated
Was this helpful?