React: React의 이벤트 시스템 이해하기
React의 이벤트 시스템 개요
합성 이벤트란 무엇입니까?
합성 이벤트는 브라우저 간 호환성을 달성하고 성능을 최적화하며 이벤트 처리를 단순화하기 위해 React에서 설계한 이벤트 처리 메커니즘입니다. 기본 브라우저 이벤트를 캡슐화하여 통합 API 및 이벤트 처리 접근 방식을 제공하고 다양한 브라우저에서 일관된 이벤트 동작을 보장합니다.
합성 이벤트의 작동 원리
이벤트 위임
React는 이벤트 위임 메커니즘을 통해 이벤트를 처리합니다. 이벤트 위임은 React가 이벤트 리스너를 각 DOM 요소에 직접 바인딩하지 않음을 의미합니다. 대신 모든 이벤트 리스너를 단일 루트 노드(일반적으로 애플리케이션의 문서 또는 루트 컨테이너)에 바인딩합니다. 사용자가 페이지와 상호작용하고 이벤트를 트리거하면 해당 이벤트가 DOM 트리를 루트 노드로 버블링하고, 여기서 React는 이벤트를 캡처하여 합성 이벤트로 래핑합니다.
이벤트 위임의 장점:
성능 최적화: 바인딩해야 하는 이벤트 핸들러 수를 줄여 메모리 사용량을 낮춥니다.
간소화된 이벤트 관리: 루트 노드에서 모든 이벤트를 관리함으로써 React는 이벤트 전파를 보다 효율적으로 처리하고 기본 동작을 방지하며 기타 이벤트 관련 작업을 수행할 수 있습니다.
이벤트 풀링
합성 이벤트의 핵심 메커니즘은 이벤트 풀링입니다. 이벤트 풀링은 이벤트가 트리거될 때마다 새 이벤트 객체를 생성하는 대신 React가 이벤트 객체를 재사용한다는 것을 의미합니다. 이벤트가 발생하면 React는 이벤트 풀에서 이벤트 객체를 가져와 초기화한 후 이벤트 핸들러에 전달합니다. 이벤트 처리가 완료되면 이벤트 객체가 정리되어 다음 이벤트에 재사용할 수 있도록 이벤트 풀로 반환됩니다.
이벤트 풀링의 장점:
- 감소된 메모리 할당: 이벤트 객체를 재사용함으로써 React는 빈번한 메모리 할당 및 가비지 수집 작업을 방지하여 특히 마우스 이동이나 스크롤과 같이 빈도가 높은 이벤트의 경우 성능을 크게 향상시킬 수 있습니다.
합성 이벤트의 수명주기
이벤트 풀링으로 인해 합성 이벤트의 수명주기는 기본 이벤트의 수명주기와 다릅니다. 일반적으로 이벤트 핸들러 함수 실행이 완료된 후 합성 이벤트 객체의 속성은 재사용을 위해 풀로 반환될 수 있도록 null로 재설정됩니다.
참고 사항:
비동기 작업: 비동기 작업 내에서 이벤트 객체에 액세스해야 하는 경우 event.persist() 메서드를 호출해야 합니다. 이렇게 하면 이벤트 개체가 풀로 반환되는 것을 방지하여 비동기 작업 중에 재설정되지 않도록 할 수 있습니다.
API 및 합성 이벤트 사용
React Synthetic Event API는 React에서 일반적으로 사용되는 기본 브라우저 이벤트와 유사한 인터페이스 세트를 제공합니다. 다음은 자주 사용되는 메소드 및 속성에 대한 자세한 소개와 함께 해당 사용 시나리오를 보여주는 예입니다.
아. 방지기본()
preventDefault() 메서드는 이벤트의 기본 동작을 방지하는 데 사용됩니다. 기본 동작은 양식이 제출될 때 페이지를 새로 고치거나 링크를 클릭할 때 새 페이지로 이동하는 등 이벤트가 발생할 때 브라우저가 일반적으로 수행하는 작업을 나타냅니다.
예: 기본 양식 제출 동작 방지
function MyForm() { const handleSubmit = e => { e.preventDefault(); // Prevent the default form submission behavior console.log('Form submission prevented'); }; return ( <form onSubmit={handleSubmit}> <input type="text" name="name" /> <button type="submit">Submit</button> </form> ); }
이 예에서 PreventDefault()가 호출되지 않은 경우 제출 버튼을 클릭하면 양식 제출이 트리거되어 페이지가 새로 고쳐집니다. PreventDefault()를 호출하면 기본 동작이 방지되므로 대신 양식 처리 논리를 사용자 정의할 수 있습니다.
ㄴ. 중지전파()
stopPropagation() 메서드는 이벤트의 추가 전파를 중지하는 데 사용됩니다. 이벤트는 일반적으로 이벤트가 트리거된 대상 요소에서 상위 요소까지 전파됩니다(이벤트 버블링). stopPropagation()을 호출하면 이러한 전파를 방지할 수 있습니다.
예: 클릭 이벤트 전파 중지
function Parent() { const handleParentClick = () => { console.log('Parent clicked'); }; return ( <div onClick={handleParentClick}> Parent Div <Child /> </div> ); } function Child() { const handleChildClick = e => { e.stopPropagation(); // Stop the event from bubbling up to the parent element console.log('Child clicked'); }; return <button onClick={handleChildClick}>Click Me</button>; }
이 예에서 버튼을 클릭하면 하위 구성 요소의 클릭 이벤트 핸들러가 트리거됩니다. 기본적으로 이벤트는 상위 구성 요소까지 버블링되고 해당 클릭 핸들러도 트리거됩니다. 하지만 Child 컴포넌트에서 stopPropagation()을 호출하면 Parent로의 이벤트 버블링을 방지할 수 있습니다.
c. target
The target property refers to the actual DOM element that triggered the event. It is commonly used to access the element that initiated the event and to handle logic related to that element.
*Example: Accessing the element that triggered the event *
function MyComponent() { const handleClick = e => { console.log('Clicked element:', e.target); }; return ( <div onClick={handleClick}> <button>Button 1</button> <button>Button 2</button> </div> ); }
In this example, when either button is clicked, the e.target in the handleClick function will point to the button element that was clicked. The target property is used to identify which specific element was clicked.
d. currentTarget
The currentTarget property refers to the DOM element to which the event handler is bound. During event handling, regardless of which child element the event bubbles to, currentTarget always points to the element that the event handler is attached to.
Example: Distinguishing between target and currentTarget
function MyComponent() { const handleClick = e => { console.log('Clicked element:', e.target); console.log('Event handler bound to:', e.currentTarget); }; return ( <div onClick={handleClick}> <button>Button 1</button> <button>Button 2</button> </div> ); }
In this example, when any button is clicked, event.target will point to the button that was clicked, while event.currentTarget will always point to the parent div element where the event handler is bound.
e. persist()
The persist() method is used to retain the event object, preventing React from reusing it. This method is typically needed in asynchronous operations.
Example: Using the event object in an asynchronous operation
function MyComponent() { const handleClick = e => { e.persist(); // Retain the event object setTimeout(() => { console.log('Button clicked:', event.target); }, 1000); }; return <button onClick={handleClick}>Click Me</button>; }
In this example, because the event object might be reused in asynchronous operations, persist() is called to retain the event object, ensuring that the event properties can be safely accessed in the setTimeout callback.
React Synthetic Event Types
React provides various types of synthetic events that cover common user interaction scenarios. Below are some commonly used synthetic event types along with examples:
a. Mouse Events
onClick: Triggered when an element is clicked.
onDoubleClick: Triggered when an element is double-clicked.
onMouseDown: Triggered when a mouse button is pressed down on an element.
onMouseUp: Triggered when a mouse button is released on an element.
onMouseMove: Triggered when the mouse is moved over an element.
onMouseEnter: Triggered when the mouse pointer enters the element's area; does not bubble.
onMouseLeave: Triggered when the mouse pointer leaves the element's area; does not bubble.
Example: Using onClick and onMouseMove
function MouseTracker() { const handleMouseMove = e => { console.log(`Mouse position: (${e.clientX}, ${e.clientY})`); }; return ( <div onMouseMove={handleMouseMove} style={{ height: '200px', border: '1px solid black' }}> Move your mouse here </div> ); } function MyApp() { return ( <div> <button onClick={() => console.log('Button clicked!')}>Click Me</button> <MouseTracker /> </div> ); }
In this example, the MouseTracker component logs the mouse position whenever it moves within the div area, while the button in the MyApp component logs a message when clicked.
b. Keyboard Events
onKeyDown: Triggered when a key is pressed down on the keyboard.
onKeyUp: Triggered when a key is released on the keyboard.
onKeyPress: Triggered when a key is pressed and held down (deprecated; it is recommended to use onKeyDown instead).
Example: Handling the onKeyDown Event
function KeyHandler() { const handleKeyDown = e => { console.log('Key pressed:', e.key); }; return <input type="text" onKeyDown={handleKeyDown} placeholder="Press any key" />; }
In this example, when the user presses any key while focused on the input field, the handleKeyDown function logs the name of the pressed key.
c. Focus Events
onFocus: Triggered when an element gains focus.
onBlur: Triggered when an element loses focus.
Example: Handling onFocus and onBlur Events
function FocusExample() { return ( <input onFocus={() => console.log('Input focused')} onBlur={() => console.log('Input blurred')} placeholder="Focus and blur me" /> ); }
In this example, when the input field gains or loses focus, a corresponding message is logged to the console.
d. Form Events
onChange: Triggered when the value of a form control changes.
onSubmit: Triggered when a form is submitted.
onInput: Triggered when the user inputs data (including actions like deleting or pasting).
Example: Handling onChange and onSubmit Events
function MyForm() { const [value, setValue] = React.useState(''); const handleChange = e => { setValue(e.target.value); }; const handleSubmit = e => { e.preventDefault(); console.log('Form submitted with value:', value); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={value} onChange={handleChange} /> <button type="submit">Submit</button> </form> ); }
In this example, as the user types into the input field, the handleChange function updates the component's state. When the form is submitted, the handleSubmit function logs the current value of the input field.
Differences Between React Events and Regular HTML Events
a. Event Naming
Native: All lowercase (e.g., onclick).
React: CamelCase (e.g., onClick).
b. Event Handler Syntax
Native events use strings to specify event handlers.
React events use functions as event handlers.
c. Preventing Default Browser Behavior
Native: can use 'return false' to prevent the browser's default behavior.
React: Instead, you must explicitly call preventDefault() to achieve this.
디. 이벤트 진행 순서
기본 이벤트가 먼저 실행되고 그 다음에 합성 이벤트가 실행됩니다. 합성 이벤트가 버블링되어 문서에 바인딩됩니다. 따라서 네이티브 이벤트와 합성 이벤트를 혼합하지 않는 것이 좋습니다. 기본 이벤트가 전파를 중지하면 합성 이벤트가 실행할 문서까지 버블링에 의존하기 때문에 합성 이벤트가 실행되지 않을 수 있습니다.
React가 합성 이벤트를 선택하는 이유
React가 합성 이벤트를 선택하는 이유는 다음과 같습니다.
브라우저 간 일관성: 합성 이벤트는 다양한 브라우저 간의 이벤트 처리 차이를 추상화하여 모든 브라우저에서 일관된 동작을 보장합니다.
성능 최적화: 이벤트 위임 및 이벤트 풀링은 이벤트 처리 오버헤드를 크게 줄여 애플리케이션 성능을 향상시킵니다.
더 나은 이벤트 관리: React는 합성 이벤트를 통해 이벤트 전파를 더 효과적으로 제어하고, 기본 동작을 방지하며, 더 효율적인 이벤트 처리를 위해 React의 일괄 업데이트 메커니즘과 긴밀하게 통합할 수 있습니다.
위 내용은 React: React의 이벤트 시스템 이해하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.
