React hook: useImperativeHandle แบบสั้นๆ

Web Development

React hook: useImperativeHandle แบบสั้นๆ

9 เดือนที่ผ่านมา

1 min read

Table of Contents

useImperativeHandle เป็น hook ที่ใช้ในการ customize ค่า instance ที่จะถูกเปิดเผยให้กับ parent component เมื่อใช้ ref ซึ่งมันจะมีประโยชน์เมื่อเราต้องการให้ parent component สามารถเข้าถึงค่าบางอย่างของ child component ได้ โดยที่ไม่ต้องเปิดเผยรายละเอียดของการทำงานภายในของ child component นั่นเอง

import React, { useRef, useImperativeHandle } from "react";
 
const Input = React.forwardRef((props, ref) => {
  const inputRef = useRef();
 
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
    value: inputRef.current.value,
  }));
 
  return <input type="text" ref={inputRef} placeholder={props.placeholder} />;
});
 
function App() {
  const inputRef = useRef();
 
  const handleClick = () => {
    inputRef.current.focus();
  };
 
  return (
    <div>
      <Input ref={inputRef} placeholder="Type here" />
      <button onClick={handleClick}>Focus input</button>
    </div>
  );
}

ในตัวอย่างนี้ เราจะกำหนด component ที่ชื่อว่า Input ซึ่งจะใช้ useImperativeHandle เพื่อเปิดเผย method ที่ชื่อว่า focus และ property ที่ชื่อว่า value ให้กับ parent component เมื่อใช้ ref ซึ่ง hook useImperativeHandle จะรับ argument 2 ตัว คือ ref object และ callback function ที่จะ return object ที่มี properties และ methods ที่ต้องการเปิดเผยให้กับ parent component

ใน component App เราจะใช้ component Input และส่ง ref object ไปให้มันด้วย และเราก็จะกำหนด function ที่ชื่อว่า handleClick ซึ่งจะเรียก method focus ของ object inputRef เมื่อมีการคลิกปุ่ม

เมื่อเรารัน code นี้ เราจะเห็น input field ที่มี placeholder text และปุ่มที่เขียนว่า “Focus input” เมื่อเราคลิกปุ่ม มันก็จะเรียก method focus ของ object inputRef และ input field ก็จะถูก focus

สรุปว่า hook useImperativeHandle จะช่วยให้เราสามารถ customize ค่า instance ที่จะถูกเปิดเผยให้กับ parent component เมื่อใช้ ref ได้ ซึ่งมันจะมีประโยชน์เมื่อเราต้องการให้ parent component สามารถเข้าถึงค่าบางอย่างของ child component ได้ โดยที่ไม่ต้องเปิดเผยรายละเอียดของการทำงานภายในของ child component นั่นเอง

Tags:

React