• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

리액트 내에서 const질문입니다.

20.11.09 06:53 작성 조회수 108

1

리액트 컴포넌트에서 상수변수로 사용시 최하단에 상수변수를 작성하였는데 Study() 함수내부의 for문에서 BOX_LIST를 어떻게 읽을수 있나요? 모듈번들링을 통해서 그 파일을 읽을수있는건가요..? 

import React, { useState, useRef } from "react";

export default function Study() {
const boxListRef = useRef({});
function onClick() {
let maxRight = 0;
let maxId = "";
for (const box of BOX_LIST) {
const ref = boxListRef.current[box.id];
if (ref) {
const rect = ref.getBoundingClientRect();
if (maxRight < rect.right) {
maxRight = rect.right;
maxId = box.id;
}
}
}
alert(`오른쪽 끝 요소는 ${maxId}`);
}
return (
<div>
<div
style={{
display: "flex",
flexWrap: "wrap",
width: "100vw",
height: "100%",
}}
>
{BOX_LIST.map(item => (
<div
key={item.id}
ref={ref => (boxListRef.current[item.id] = ref)}
style={{
flex: "0 0 auto",
width: item.width,
height: 100,
backgroundColor: "yellow",
border: "solid 1px red",
}}
>{`box_${item.id}`}</div>
))}
</div>
<button onClick={onClick}>오른쪽 끝 요소는?</button>
</div>
);
}

const BOX_LIST = [
{ id: 1, width: 70 },
{ id: 2, width: 100 },
{ id: 3, width: 80 },
{ id: 4, width: 100 },
{ id: 5, width: 90 },
{ id: 6, width: 60 },
{ id: 1, width: 120 },
];

답변 1

답변을 작성해보세요.

0

안녕하세요
Study 함수 내부에서 BOX_LIST 에 접근할 때는 이미 BOX_LIST 의 값이 할당된 후입니다
그래서 BOX_LIST 값을 읽을 수 있습니다. 제가 질문을 제대로 이해한건지 모르겠네요;;;
참고로 함수에서 외부 변수에 접근하는 경우에 대한 자세한 설명은 lexcial environment 부분에서 확인하실 수 있습니다.