첫번째 조건
- 부모components에서 ref선언.
- 부모component의 dom elements를 자식 컴포넌트에서 제어하기.
import { useRef } from 'react'
import ChildrenPage from './ChildrenPage'
const ParentsPage = () => {
const inputRef = useRef<HTMLInputElement>(null)
return (
<div>
<div>
ParentsPage <input type="text" ref={inputRef} />
</div>
{/* <ChildrenPage inputRef={inputRef} ref={buttonRef} /> */}
<ChildrenPage inputRef={inputRef} />
</div>
)
}
export default ParentsPage
import { useEffect, RefObject } from 'react'
interface Props {
inputRef: RefObject<HTMLInputElement>
}
const ChildrenPage = ({ inputRef }: Props) => {
useEffect(() => {
if (inputRef.current) inputRef?.current.focus()
}, [])
return <div>ChildrenPage</div>
}
export default ChildrenPage
- 이거 redux에서도 되나?
되긴 된다 근데 저장되는 사이즈가 너무 커서 사용하지 말라는 경고가 뜬다.
암튼 그래서 비추함.
이거 쓰려면 걍 종속성형식으로 부모에서 자식으로 다이렉트로 박아넣는 법으로만 써야하는듯.
🤮🤮🤮🤮🤮🤮🤮🤮🤮🤮🤮🤮
두번째 조건
- 부모 components에서 ref선언.
- 자식 component의 dom elements를 부모 component에서 제어하기
import { useEffect, useRef } from 'react'
import ChildrenPage from './ChildrenPage'
const TestPage = () => {
const buttonRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (buttonRef.current) buttonRef.current?.focus()
}, [])
return (
<div>
<ChildrenPage ref={buttonRef} />
</div>
)
}
export default TestPage
import React, { forwardRef, useEffect, RefObject } from 'react'
const ChildrenPage = forwardRef(
(props: Props, ref: React.ForwardedRef<HTMLInputElement>) => {
return (
<div>
ChildrenPage
<input type="text" ref={ref} />
</div>
)
},
)
export default ChildrenPage