본문 바로가기
Programming/Cross-platform

[Tauri] React에서 Tauri event handling 하기

by 째스터 2024. 5. 8.
728x90

react 컴포넌트에서 keydown event를 핸들링하는 방법은 아래와 같다.

useEffect(() => {
  const handleKeydown = function (event: KeyboardEvent): void {
    if ((event.ctrlKey || event.metaKey) && event.key === 's') {
      event.preventDefault()
      void saveFile()
    }
  }

  window.addEventListener('keydown', handleKeydown)
  return () => {
    window.removeEventListener('keydown', handleKeydown)
  }
}, [])

 

React에서 Tauri 이벤트를 핸들링하는 방법은 다음과 같다.
file-drop이라는 타우리 event를 핸들링하는 예시다(https://tauri.app/v1/api/js/event/).

useEffect(() => {
  const unlisten = listen('tauri://file-drop', (event: Event<string[]>) => {
    const filePath = event.payload[0]
    void loadFile(filePath)
  })
  return () => {
    void unlisten.then(f => { f() })
  }
}, [])

흠.. 뭔가 예쁘지 않은 느낌이다.
특히 clean-up 시 이전 글처럼 별도 함수를 두면 더 복잡해지기 때문에 Promise.then을 사용했다.


https://tauri.app/v1/guides/features/events/

 

Events | Tauri Apps

The Tauri event system is a multi-producer multi-consumer communication primitive that allows message passing between the frontend and the backend.

tauri.app

 

728x90

댓글