junsobi

Menu

Close

컴포넌트 맵핑과 속성 관리 개선

도형 렌더링 최적화를 위한 컴포넌트 맵핑 기법과 공통 속성 관리 방식을 알아봅니다.

List

이미지

1️⃣ 컴포넌트 맵핑을 활용한 도형 렌더링 최적화

📌 문제점: 각 도형에 대해 공통된 렌더링 로직 반복

기존에는 각 도형별로 렌더링 로직이 중복되어 있어서, 도형을 추가할 때마다 렌더링 로직을 반복적으로 작성해야 했습니다. 예를 들어, DrawEllipse, DrawRect, DrawPolygon은 각각 다른 방식으로 렌더링되었고, 도형이 많아질수록 유지보수가 어려워졌습니다.

✅ 해결 방법: 컴포넌트 맵핑을 활용한 렌더링 로직 최적화

컴포넌트 맵핑 기법을 적용하여 도형별 렌더링 로직을 객체화하여 관리할 수 있도록 변경했습니다. 도형 타입에 따라 동적으로 렌더링할 클래스를 선택하는 방식으로 리팩토링하여 코드의 간결성과 확장성을 높였습니다.

🎯 컴포넌트 맵핑을 적용한 코드

1. 도형별 렌더링 컴포넌트 맵핑
const shapeComponents: Record<Shape['type'], React.ElementType> = {
  'free-draw': DrawLine,
  line: DrawLine,
  ellipse: DrawEllipse,
  rect: DrawRect,
  polygon: DrawPolygon
};
2. 동적 렌더링 적용
const ShapeRenderer = ({ shape }: { shape: Shape }) => {
  const Component = shapeComponents[shape.type];
  return Component ? <Component shape={shape} /> : null;
};

🚀 효과

  • 코드 간결화: 도형별 렌더링 로직을 하나로 통합하여 코드가 간결해짐
  • 확장성 증가: 새로운 도형을 추가할 때, 맵핑 테이블만 수정하면 됨
  • 유지보수성 향상: 공통된 렌더링 로직을 변경하면 여러 도형에서 일관성 있게 동작하여 유지보수성이 개선됨

2️⃣ 도형 속성 관리: createShapeProps로 공통 로직 처리

📌 문제점: 도형별 속성 관리가 복잡

각 도형에 필요한 속성이 서로 다르며, 도형을 그릴 때마다 속성을 설정해야 하는 문제가 있었습니다. 예를 들어, linepoints만 필요하지만, ellipseradiusX, radiusY 속성이 추가됩니다.

✅ 해결 방법: 공통 속성 관리 함수 createShapeProps 도입

도형 속성 설정 로직을 createShapeProps 함수로 통합하여, 불필요한 중복 코드를 제거했습니다.

const createShapeProps = (
  tool: ToolType,
  currentShape: number[],
  color: string,
  thickness: number,
  polygonPoints: number[][]
): Shape => {
  switch (tool) {
    case 'free-draw':
    case 'line':
      return { id: 'temp', color, thickness, type: tool, points: currentShape };
    case 'ellipse':
      return {
        id: 'temp',
        color,
        thickness,
        type: 'ellipse',
        x: currentShape[0],
        y: currentShape[1],
        radiusX: Math.abs(currentShape[2]),
        radiusY: Math.abs(currentShape[3])
      };
    case 'rect':
      return {
        id: 'temp',
        color,
        thickness,
        type: 'rect',
        x: currentShape[0],
        y: currentShape[1],
        width: currentShape[2],
        height: currentShape[3]
      };
    case 'polygon':
      return {
        id: 'temp',
        color,
        thickness,
        type: 'polygon',
        points: [
          ...polygonPoints.map((p) => [...p]),
          [currentShape[2], currentShape[3]]
        ],
        closed: false
      };
    default:
      throw new Error(`Unsupported tool type: ${tool}`);
  }
};

🚀 효과

  • 속성 설정 로직 통합: 일관성과 재사용성이 증가
  • 확장성 향상: 새로운 도형 추가 시 createShapeProps만 수정하면 됨
  • 중복 코드 제거: 코드 관리가 용이해짐

이처럼 컴포넌트 맵핑과 공통 속성 관리 기법을 활용하면 도형 렌더링 로직을 더욱 체계적으로 관리할 수 있습니다. 이를 통해 코드의 가독성을 높이고 유지보수성을 개선할 수 있습니다.


관련 프로젝트 저장소 : https://github.com/junsobi/DrawingTool-with-KonvaReact


이미지