1. forwardRef
forwardRef is React hook which can allow parent component to pass HTML Element through a child component to access child's underlying DOM node or instance directly.
2. useImperativeHandle
useImperativeHandle hook allows a child component to customize instance value that is exposed to parent component when using ref.
3. Sample Code
import logo from './logo.svg';
import './App.css';
import React from 'react';
import { forwardRef, useImperativeHandle, useState, useEffect, useRef, useMemo, useCallback, memo} from 'react';
import Timer from './component/Timer.js';
import Page from './component/Page.jsx'
import {ThemeContext} from './context/ThemeContext.js'
const Input = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => ({
alert: () => alert(props.value) //Parent component can call this method
}),
[props.value]
)
return <input ref={ref} {...props}/>
})
function App() {
const inputRef = useRef() //refer child component using inputRef
const [text, setText] = useState('')
function handleClick(){
inputRef.current.alert()
}
function handleChange(e){
setText(e.target.value)
}
return (
<>
<Input ref={inputRef} value={text} onChange={handleChange} />
<button onClick={handleClick}>Focus</button>
</>
)
}
export default App;
0 댓글