Web Development
React hook: useRef แบบสั้นๆ
29 กรกฎาคม 2023 • 1 นาที
0

Table of Contents
useRef ช่วยให้เราสร้าง ref object ที่เปลี่ยนแปลงได้ ที่จะยังคงอยู่ตลอดรอบการ render ของ component นั้นๆ และเราสามารถเก็บค่าไว้ใน ref object นั้นๆ และเรียกใช้ค่านั้นๆ ได้โดยที่ไม่ต้องทำให้เกิดการ render ใหม่
ตัวอย่างการใช้ useRef ในการเข้าถึงค่าของ input element:

import React, { useRef } from "react";
function InputWithFocus() {
const inputRef = useRef();
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
ในตัวอย่างนี้ เราสร้าง component ชื่อ InputWithFocus ซึ่งจะสร้าง ref object ด้วย useRef hook และเชื่อมต่อกับ element input และเราจะใช้ ref object นั้นๆ ในการ focus input เมื่อคลิกปุ่ม Focus Input
Tags:React
คลิกเพื่อแสดงความคิดเห็น