반응형
리액션 후크를 사용하여 "refs"를 동적으로 추가하는 방법?
그래서 나는 데이터 배열을 가지고 있고 그 데이터로 구성요소 목록을 만들고 있다.생성된 각 요소에 대한 참조를 통해 높이를 계산하고 싶다.클래스 구성 요소로 할 줄 알지만 리액션 후크로 하고 싶다.
내가 하고 싶은 일을 설명하는 예는 다음과 같다.
import React, {useState, useCallback} from 'react'
const data = [
{
text: 'test1'
},
{
text: 'test2'
}
]
const Component = () => {
const [height, setHeight] = useState(0);
const measuredRef = useCallback(node => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
}, []);
return (
<div>
{
data.map((item, index) =>
<div ref={measuredRef} key={index}>
{item.text}
</div>
)
}
</div>
)
}
네 의도를 완전히 이해하진 못했지만 네가 원하는 건 이런 거야
const {
useState,
useRef,
createRef,
useEffect
} = React;
const data = [
{
text: "test1"
},
{
text: "test2"
}
];
const Component = () => {
const [heights, setHeights] = useState([]);
const elementsRef = useRef(data.map(() => createRef()));
useEffect(() => {
const nextHeights = elementsRef.current.map(
ref => ref.current.getBoundingClientRect().height
);
setHeights(nextHeights);
}, []);
return (
<div>
{data.map((item, index) => (
<div ref={elementsRef.current[index]} key={index} className={`item item-${index}`}>
{`${item.text} - height(${heights[index]})`}
</div>
))}
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Component />, rootElement);
.item {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ccc;
}
.item-0 {
height: 25px;
}
.item-1 {
height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id="root"/>
나는 작은 것을 만들었다.npm
a를 표시하는 패키지React Hook
종종 같은 문제에 부딪히면서 동적으로 설정과 ref를 처리하는 것.
npm i use-dynamic-refs
여기 간단한 예가 있다.
import React, { useEffect } from 'react';
import useDynamicRefs from 'use-dynamic-refs';
const Example = () => {
const foo = ['random_id_1', 'random_id_2'];
const [getRef, setRef] = useDynamicRefs();
useEffect(() => {
// Get ref for specific ID
const id = getRef('random_id_1');
console.log(id)
}, [])
return (
<>
{/* Simple set ref. */}
<span ref={setRef('random_id_3')}></span>
{/* Set refs dynamically in Array.map() */}
{ foo.map( eachId => (
<div key={eachId} ref={setRef(eachId)}>Hello {eachId}</div>))}
</>
)
}
export default Example;
각 항목에 대해 별도의 후크 세트를 사용해야 하며, 이는 품목에 대한 구성 요소를 정의해야 함을 의미한다(또는 루프 내에서 후크를 사용 중, 허용되지 않음).
const Item = ({ text }) => {
const ref = useRef()
const [ height, setHeight ] = useState()
useLayoutEffect(() => {
setHeight( ref.current.getBoundingClientRect().height )
}, [])
return <div ref={ref}>{text}</div>
}
참조URL: https://stackoverflow.com/questions/55995760/how-to-add-refs-dynamically-with-react-hooks
반응형
'programing' 카테고리의 다른 글
여러 번 마운트된 반응 및 반응 라우터 비동기 구성 요소(구성 요소DidMount를 여러 번 호출함) (0) | 2022.03.31 |
---|---|
Python에서 XPath를 사용하는 방법? (0) | 2022.03.31 |
ReactRedex TypeScript 앱이 iPhone 6 iOS 12.0.1(공백색 화면인 경우)을 제외한 모든 곳에서 작동하는 이유는? (0) | 2022.03.31 |
왜 Python은 제곱근에 대해 "잘못된" 대답을 하는가?파이썬 2의 정수분할이란? (0) | 2022.03.31 |
별도의 구성 요소에 가져오기 기능 삽입 (0) | 2022.03.31 |