리스트에서 특정 요소에 접근(Ref)
리스트 렌더링에서 Ref 객체를 사용해서 특정 요소에 접근할 때 아래와 같이 사용한다.
class AppNavigation extends React.Component {
// Ref 객체 생성
listRef = React.createRef()
componentDidMount() {
// 렌더링 이후 시점에 접근을 해야 current에 참조된 요소가 할당 된다.
console.log(this.listRef.current)
}
render() {
const { items } = this.context.navigation
return (
<>
<ul className="resetList">
{items.map(({ link, text }, index) => {
return (
<li key={index} id={index}>
<a
// index와 비교해서 원하는 인덱스에 listRef 객체가 참조되어 current에 요소가 담기도록 한다.
ref={index === 0 ? this.listRef : null}
href={link}
>
{text}
</a>
</li>
)
})}
</ul>
</>
)
}
}

Last updated
Was this helpful?