재우니의 블로그

 

View Module

ViewModule을 상속받고 컴포넌트 메소드(React 함수 컴포넌트)를 정의함으로써 View에서 모듈을 구현하는데 사용할 수 있습니다.

현재 ViewModule의 임의의 메소드를 컴포넌트에 주입할 수도 있고, useConnector를 사용하여 현재 공유 모듈 상태 또는 다른 의존 모듈의 상태를 주입할 수도 있습니다.

 

interface Todo {
  text: string;
  completed: boolean;
}

@injectable()
class TodoView extends ViewModule {
  @state
  list: Todo[] = [];

  addTodo(text: string) {
    this.list.push({
      text,
      completed: false,
    });
  }

  @action
  toggleTodo(key: number, value: boolean) {
    this.list[key].completed = !value;
  }

  component() {
    const list = useConnector(() => this.list);
    return (
      <ul>
        {this.list.map(({ text, completed }, key) => (
          <li key={key} onClick={() => this.toggleTodo(key, completed)}>
            {text}
          </li>
        ))}
      </ul>
    );
  }
}

useConnector은 자동으로 얕은 비교 상태 객체를 돌려주는 일도 지원하고 있습니다.

 

const { list, visibilityFilter } = useConnector(() => ({
  list: this.list,
  visibilityFilter: this.visibilityFilter,
}));

ViewModule은 상속을 지원하는데 컴포넌트 메소드 구현에 기반한 함수 컴포넌트는 jsx를 사용하지 않고 슈퍼클래스 컴포넌트 메소드에 기반한 컴포넌트와 같은 방법으로 호출해야 한다는 점을 주의해야 합니다.

 

@injectable()
class BaseFooView extends ViewModule {
  component() {
    return <span>foo</span>;
  }
}

class FooView extends BaseFooView {
  component() {
    return (
      <>
        <span>foo</span>
        {
          super.component()
          // Don't make it: <super.component />
        }
      </>
    );
  }
}