Hyphen, underscore, or camelCase as word delimiter in URIs?
useImperativeHandle
forwardRef와 함께 사용하여
부모에 노출시킬 함수를 정하는 기능
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
// 자식 컴포넌트
const FocusInput = forwardRef((props, ref) => {
const inputRef = useRef();
// useImperativeHandle을 사용하여 부모에게 노출할 함수를 지정
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
blur: () => {
inputRef.current.blur();
}
}));
return <input ref={inputRef} />;
});
// 부모 컴포넌트
const ParentComponent = () => {
const childRef = useRef();
const handleFocus = () => {
// 자식 컴포넌트의 포커스 함수 호출
childRef.current.focus();
};
const handleBlur = () => {
// 자식 컴포넌트의 블러 함수 호출
childRef.current.blur();
};
return (
<div>
<button onClick={handleFocus}>Focus Input</button>
<button onClick={handleBlur}>Blur Input</button>
<FocusInput ref={childRef} />
</div>
);
};
export default ParentComponent;
useImperativeHandle**은 주로 부모 컴포넌트에서 자식 컴포넌트의 인스턴스에 직접 접근할 때 사용됩니다.useImperativeHandle**을 사용하여 외부에서 접근 가능한 인터페이스를 제공하는 경우가 있습니다.useImperativeHandle**를 남용하면 컴포넌트 간의 결합도가 높아질 수 있습니다.useImperativeHandle**을 남용하면 이 원칙을 어기게 될 수 있습니다.useImperativeHandle**의 의존성 배열을 주의해서 관리해야 합니다.Unlighthouse is a tool to scan your entire site with Google Lighthouse in 2 minutes (on average). Open source, fully configurable with minimal setup.