[TS 과제 챌린지] Menu Slider & Modal - 트러블슈팅

조민호·2023년 10월 27일
0

Element.classList.contains 와 기능이 다르다!!!

contains() 메서드는 DOM 노드가 다른 노드의 하위 항목인지 여부를 확인하는 데 사용됩니다. 이 메서드는 부모 요소에서 호출되며, 매개 변수로 전달된 자식 요소가 포함되어 있는지 여부를 반환합니다.

예를 들어, 다음과 같은 HTML 구조가 있다고 가정해봅시다.

<div id="parent">
  <p id="child">Hello, world!</p>
</div>

이 경우, #parent 요소는 #child 요소의 부모 요소입니다. 따라서 #parent 요소에서 contains() 메서드를 호출하여 #child 요소가 포함되어 있는지 확인할 수 있습니다.

const parent = document.getElementById('parent');
const child = document.getElementById('child');

console.log(parent.contains(child)); // true
console.log(child.contains(parent)); // false

contains() 메서드는 true 또는 false를 반환합니다. true가 반환되면 부모 요소가 자식 요소를 포함하고 있으며, false가 반환되면 그렇지 않습니다.

이 메서드는 이벤트 처리기를 작성할 때 특히 유용합니다. 예를 들어, 이벤트 리스너에서 클릭된 요소가 특정 부모 요소에 속해 있는지 확인하여 원하는 동작을 수행할 수 있습니다.

이럴 때 type assertion 써야 함

안쓰면 false리터럴 값으로 고정이

const toggleButton = document.getElementById('toggle') as HTMLButtonElement;
const closeButton = document.getElementById('close') as HTMLButtonElement;
const openButton = document.getElementById('open') as HTMLButtonElement;
const modal = document.getElementById('modal') as HTMLDivElement;
const navButton = document.getElementById('navbar') as HTMLDivElement;

type statesType = {
  isToggle: boolean;
};

const useState = <T extends statesType>(status: T): [() => T, (state: T) => void] => {
  let initialState = status;

  const state = () => initialState as T;

  const setState = (newState: T) => {
    initialState = newState;
  };

  return [state, setState];
};

const [navToggle, setNavToggle] = useState({ isToggle: false } **as statesType**);

setNavToggle({ isToggle: true})
profile
웰시코기발바닥

0개의 댓글