All built-in browser components, such as <div>, support some common props and events.
<div>와 같은 모든 브라우저 빌트인 컴포넌트는 몇 가지 일반적인 props와 이벤트를 지원합니다.
- Reference참조
- Common components (e.g.
<div>) 기본 컴포넌트 (예:<div>) refcallback functionref콜백 함수- React event object React 이벤트 객체
AnimationEventhandler functionAnimationEvent핸들러 함수ClipboardEventhandler functionClipboardEvent핸들러 함수CompositionEventhandler functionCompositionEvent핸들러 함수DragEventhandler functionDragEvent핸들러 함수FocusEventhandler functionFocusEvent핸들러 함수Eventhandler functionEvent핸들러 함수InputEventhandler functionInputEvent핸들러 함수KeyboardEventhandler functionKeyboardEvent핸들러 함수MouseEventhandler functionMouseEvent핸들러 함수PointerEventhandler functionPointerEvent핸들러 함수TouchEventhandler functionTouchEvent핸들러 함수TransitionEventhandler functionTransitionEvent핸들러 함수UIEventhandler functionUIEvent핸들러 함수WheelEventhandler functionWheelEvent핸들러 함수
- Common components (e.g.
- Usage사용법
Reference참조
Common components (e.g. <div>) 기본 컴포넌트 (예: <div>)
<div className="wrapper">Some content</div>See more examples below. 아래에서 더 많은 예시를 확인하세요.
Props
These special React props are supported for all built-in components: 아래의 특별한 React props는 모든 빌트인 컴포넌트에서 지원됩니다:
-
children: A React node (an element, a string, a number, a portal, an empty node likenull,undefinedand booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify thechildrenprop implicitly by nesting tags like<div><span /></div>.children: React 노드(엘리먼트, 문자열, 숫자, portal,null,undefined및 boolean과 같은 빈 노드 또는 기타 React 노드의 배열). 컴포넌트 내부의 콘텐츠를 지정합니다. JSX를 사용할 때 일반적으로<div><span /></div>와 같은 태그를 중첩하여 암묵적으로childrenprop을 지정합니다. -
dangerouslySetInnerHTML: An object of the form{ __html: '<p>some html</p>' }with a raw HTML string inside. Overrides theinnerHTMLproperty of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn’t trusted (for example, if it’s based on user data), you risk introducing an XSS vulnerability. Read more about usingdangerouslySetInnerHTML.dangerouslySetInnerHTML: 내부에 원시 HTML 문자열이 있는{ __html: '<p>일부 html</p>' }형식의 객체로, 내부에 원시 HTML 문자열이 있습니다. DOM 노드의innerHTML속성을 재정의하고 전달된 HTML을 내부에 표시합니다. 이 함수는 매우 주의해서 사용해야 합니다! 내부 HTML을 신뢰할 수 없는 경우(예: 사용자 데이터를 기반으로 하는 경우) XSS 취약점이 발생할 위험이 있습니다.dangerouslySetInnerHTML사용에 대해 자세히 알아보세요. -
ref: A ref object fromuseReforcreateRef, or arefcallback function, or a string for legacy refs. Your ref will be filled with the DOM element for this node. Read more about manipulating the DOM with Refs.ref:useRef또는createRef의 ref 객체,ref콜백 함수, 또는 레거시 ref에 대한 문자열. ref는 이 노드의 DOM 엘리먼트로 채워집니다. ref로 DOM을 조작하는 방법에 대해 자세히 알아보세요. -
suppressContentEditableWarning: A boolean. Iftrue, suppresses the warning that React shows for elements that both havechildrenandcontentEditable={true}(which normally do not work together). Use this if you’re building a text input library that manages thecontentEditablecontent manually.suppressContentEditableWarning: 불리언.true이면, 일반적으로 함께 작동하지 않는 (일반적으로 함께 작동하지 않는)children과contentEditable={true}가 모두 있는 엘리먼트에 대해 React가 표시하는 경고를 억제합니다. 이 값을 사용하면contentEditable콘텐츠를 수동으로 관리하는 텍스트 입력 라이브러리를 빌드할 때 사용합니다. -
suppressHydrationWarning: A boolean. If you use server rendering, normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you setsuppressHydrationWarningtotrue, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don’t overuse it. Read about suppressing hydration errors.suppressHydrationWarning: 불리언. 서버 렌더링을 사용하는 경우 일반적으로 서버와 클라이언트가 서로 다른 콘텐츠를 렌더링할 때 경고가 표시됩니다. 타임스탬프와 같은 일부 드문 경우에서는 정확한 일치를 보장하기가 매우 어렵거나 불가능합니다.suppressHydrationWarning을true로 설정하면 React는 해당 엘리먼트의 속성과 콘텐츠가 일치하지 않을 때 경고하지 않습니다. 이는 한 단계 깊이에서만 작동하며, 탈출구로 사용하기 위한 것입니다. 과도하게 사용하지 마세요. hydration 오류 억제에 대해 자세히 알아보세요. -
style: An object with CSS styles, for example{ fontWeight: 'bold', margin: 20 }. Similarly to the DOMstyleproperty, the CSS property names need to be written ascamelCase, for examplefontWeightinstead offont-weight. You can pass strings or numbers as values. If you pass a number, likewidth: 100, React will automatically appendpx(“pixels”) to the value unless it’s a unitless property. We recommend usingstyleonly for dynamic styles where you don’t know the style values ahead of time. In other cases, applying plain CSS classes withclassNameis more efficient. Read more aboutclassNameandstyle.style: CSS 스타일이 있는 객체(예:{ fontWeight: 'bold', margin: 20 }). DOMstyle프로퍼티와 마찬가지로 CSS 프로퍼티 이름도font-weight대신fontWeight와 같이camelCase로 작성해야 합니다. 문자열이나 숫자를 값으로 전달할 수 있습니다.width: 100과 같이 숫자를 전달하면 React는 단위가 없는 프로퍼티가 아니라면 값에 자동으로px(“픽셀”)를 추가합니다. 스타일 값을 미리 알 수 없는 동적 스타일에만style을 사용하는 것을 권장합니다. 그 외의 경우에는className과 함께 일반 CSS 클래스를 적용하는 것이 더 효율적입니다.className과style로 CSS를 적용하는 방법에 대해 자세히 알아보세요.
These standard DOM props are also supported for all built-in components: 아래의 표준 DOM props는 모든 빌트인 컴포넌트에서도 지원됩니다:
-
accessKey: A string. Specifies a keyboard shortcut for the element. Not generally recommended.accessKey: 문자열. 엘리먼트의 키보드 단축키를 지정합니다. 일반적으로 권장하지 않습니다. -
aria-*: ARIA attributes let you specify the accessibility tree information for this element. See ARIA attributes for a complete reference. In React, all ARIA attribute names are exactly the same as in HTML.aria-*: ARIA 속성을 사용하면 이 엘리먼트에 대한 접근성 트리 정보를 지정할 수 있습니다. 전체 내용은 ARIA attributes를 참조하세요. React에서 모든 ARIA 어트리뷰트 이름은 HTML에서와 완전히 동일합니다. -
autoCapitalize: A string. Specifies whether and how the user input should be capitalized.autoCapitalize: 문자열. 사용자 입력을 대문자로 표시할지 여부와 방법을 지정합니다. -
className: A string. Specifies the element’s CSS class name. Read more about applying CSS styles.className: 문자열. 엘리먼트의 CSS 클래스 이름을 지정합니다. CSS 스타일 적용에 대해 자세히 알아보세요. -
contentEditable: A boolean. Iftrue, the browser lets the user edit the rendered element directly. This is used to implement rich text input libraries like Lexical. React warns if you try to pass React children to an element withcontentEditable={true}because React will not be able to update its content after user edits.contentEditable: 불리언.true이면 브라우저는 사용자가 렌더링된 엘리먼트를 직접 편집할 수 있도록 허용합니다. 이것은 Lexical과 같은 리치 텍스트 입력 라이브러리를 구현하는 데 사용됩니다. React는 사용자가 편집한 후에 React가 그 내용을 업데이트할 수 없기 때문에contentEditable={true}가 있는 엘리먼트에 React 자식을 전달하려고 하면 경고를 표시합니다. -
data-*: Data attributes let you attach some string data to the element, for exampledata-fruit="banana". In React, they are not commonly used because you would usually read data from props or state instead.data-*: 데이터 속성을 사용하면 엘리먼트에 일부 문자열 데이터를 첨부할 수 있습니다(예:data-fruit="banana"). React에서는 일반적으로 프로퍼티나 state에서 데이터를 읽어오기 때문에 일반적으로 사용되지는 않습니다. -
dir: Either'ltr'or'rtl'. Specifies the text direction of the element.dir:'ltr'또는'rtl'. 엘리먼트의 텍스트 방향을 지정합니다. -
draggable: A boolean. Specifies whether the element is draggable. Part of HTML Drag and Drop API.draggable: 불리언. 엘리먼트를 드래그할 수 있는지 여부를 지정합니다. HTML 드래그 앤 드롭 API의 일부입니다. -
enterKeyHint: A string. Specifies which action to present for the enter key on virtual keyboards.enterKeyHint: 문자열. 가상 키보드의 엔터 키에 표시할 동작을 지정합니다. -
htmlFor: A string. For<label>and<output>, lets you associate the label with some control. Same asforHTML attribute. React uses the standard DOM property names (htmlFor) instead of HTML attribute names.htmlFor: 문자열.<label>및<output>의 경우, 레이블을 일부 컨트롤과 연결할 수 있습니다.forHTML 속성과 동일합니다. React는 HTML 속성의 이름 대신 표준 DOM 프로퍼티 이름(htmlFor)을 사용합니다. -
hidden: A boolean or a string. Specifies whether the element should be hidden.hidden: 불리언 또는 문자열. 엘리먼트의 숨김 여부를 지정합니다. -
id: A string. Specifies a unique identifier for this element, which can be used to find it later or connect it with other elements. Generate it withuseIdto avoid clashes between multiple instances of the same component.id: 문자열. 나중에 찾거나 다른 엘리먼트와 연결하는 데 사용할 수 있는 이 엘리먼트의 고유 식별자를 지정합니다. 동일한 컴포넌트의 여러 인스턴스 간의 충돌을 방지하려면useId로 생성합니다. -
is: A string. If specified, the component will behave like a custom element.is: 문자열. 지정하면 컴포넌트가 커스텀 엘리먼트처럼 작동합니다. -
inputMode: A string. Specifies what kind of keyboard to display (for example, text, number or telephone).inputMode: 문자열. 표시할 키보드의 종류(예: 텍스트, 숫자 또는 전화)를 지정합니다. -
itemProp: A string. Specifies which property the element represents for structured data crawlers.itemProp: 문자열입니다. 구조화된 데이터 크롤러에 대해 엘리먼트가 나타내는 속성을 지정합니다. -
lang: A string. Specifies the language of the element.lang: 문자열입니다. 엘리먼트의 언어를 지정합니다. -
onAnimationEnd: AnAnimationEventhandler function. Fires when a CSS animation completes.onAnimationEnd:AnimationEvent핸들러 함수. CSS 애니메이션 종료시 호출됩니다. -
onAnimationEndCapture: A version ofonAnimationEndthat fires in the capture phase.onAnimationEndCapture: 캡쳐 단계에서 실행되는 버전의onAnimationEnd입니다. -
onAnimationIteration: AnAnimationEventhandler function. Fires when an iteration of a CSS animation ends, and another one begins.onAnimationIteration:AnimationEvent핸들러 함수. CSS 애니메이션의 이터레이션 종료시 및 다른 이터레이션 시작시 호출됩니다. -
onAnimationIterationCapture: A version ofonAnimationIterationthat fires in the capture phase.onAnimationIterationCapture: 캡쳐 단계에서 실행되는 버전의onAnimationIteration입니다. -
onAnimationStart: AnAnimationEventhandler function. Fires when a CSS animation starts.onAnimationStart:AnimationEvent핸들러 함수. CSS 애니메이션 시작시 호출됩니다. -
onAnimationStartCapture:onAnimationStart, but fires in the capture phase.onAnimationStartCapture: 캡쳐 단계에서 실행되는 버전의onAnimationStart입니다. -
onAuxClick: AMouseEventhandler function. Fires when a non-primary pointer button was clicked.onAuxClick:MouseEvent핸들러 함수. 비주요 버튼 클릭시 호출됩니다. -
onAuxClickCapture: A version ofonAuxClickthat fires in the capture phase.onAuxClickCapture: 캡쳐 단계에서 실행되는 버전의onAuxClick입니다. -
onBeforeInput: AnInputEventhandler function. Fires before the value of an editable element is modified. React does not yet use the nativebeforeinputevent, and instead attempts to polyfill it using other events.onBeforeInput:InputEvent핸들러 함수. 편집 가능한 엘리먼트가 수정되기 전에 호출됩니다. React는 아직 nativebeforeinput이벤트를 사용하지 않으며, 대신 다른 이벤트를 폴리필하여 구현하고 있습니다. -
onBeforeInputCapture: A version ofonBeforeInputthat fires in the capture phase.onBeforeInputCapture: 캡쳐 단계에서 실행되는 버전의onBeforeInput입니다. -
onBlur: AFocusEventhandler function. Fires when an element lost focus. Unlike the built-in browserblurevent, in React theonBlurevent bubbles.onBlur: AFocusEvent핸들러 함수. 엘리먼트가 초점을 잃을 때 호출됩니다. 브라우저 빌트인blur이벤트와 달리, React의onBlur이벤트는 버블이 발생합니다. -
onBlurCapture: A version ofonBlurthat fires in the capture phase.onBlurCapture: 캡쳐 단계에서 실행되는 버전의onBlur입니다. -
onClick: AMouseEventhandler function. Fires when the primary button was clicked on the pointing device.onClick:MouseEvent핸들러 함수. 포인팅 디바이스에서 주요 버튼 클릭시 호출됩니다. -
onClickCapture: A version ofonClickthat fires in the capture phase.onClickCapture: 캡쳐 단계에서 실행되는 버전의onClickthat fires in the capture phase. -
onCompositionStart: ACompositionEventhandler function. Fires when an input method editor starts a new composition session.onCompositionStart:CompositionEvent핸들러 함수. input method editor(IME)가 새 조합 세션을 시작할 때 호출됩니다. -
onCompositionStartCapture: A version ofonCompositionStartthat fires in the capture phase.onCompositionStartCapture: 캡쳐 단계에서 실행되는 버전의onCompositionStart입니다. -
onCompositionEnd: ACompositionEventhandler function. Fires when an input method editor completes or cancels a composition session.onCompositionEnd:CompositionEvent핸들러 함수. IME가 세션을 종료 또는 취소할 때 호출됩니다. -
onCompositionEndCapture: A version ofonCompositionEndthat fires in the capture phase.onCompositionEndCapture: 캡쳐 단계에서 실행되는 버전의onCompositionEnd입니다. -
onCompositionUpdate: ACompositionEventhandler function. Fires when an input method editor receives a new character.onCompositionUpdate: ACompositionEvent핸들러 함수. IME가 새 문자를 수신할 때 호출됩니다. -
onCompositionUpdateCapture: A version ofonCompositionUpdatethat fires in the capture phase.onCompositionUpdateCapture:캡쳐 단계에서 실행되는 버전의onCompositionUpdatethat fires in the capture phase. -
onContextMenu: AMouseEventhandler function. Fires when the user tries to open a context menu.onContextMenu:MouseEvent핸들러 함수. 사용자가 컨텍스트 메뉴를 열고자 할 때 호출됩니다. -
onContextMenuCapture: A version ofonContextMenuthat fires in the capture phase.onContextMenuCapture: 캡쳐 단계에서 실행되는 버전의onContextMenu입니다. -
onCopy: AClipboardEventhandler function. Fires when the user tries to copy something into the clipboard.onCopy: AClipboardEvent핸들러 함수. 사용자가 무언가를 클립보드로 복사하려고 할 때 호출됩니다. -
onCopyCapture: A version ofonCopythat fires in the capture phase.onCopyCapture: 캡쳐 단계에서 실행되는 버전의onCopy입니다. -
onCut: AClipboardEventhandler function. Fires when the user tries to cut something into the clipboard.onCut:ClipboardEvent핸들러 함수. 사용자가 클립보드에서 무언가를 잘라내고자 할 때 호출됩니다. -
onCutCapture: A version ofonCutthat fires in the capture phase.onCutCapture: 캡쳐 단계에서 실행되는 버전의onCut입니다. -
onDoubleClick: AMouseEventhandler function. Fires when the user clicks twice. Corresponds to the browserdblclickevent.onDoubleClick:MouseEvent핸들러 함수. 사용자가 두 번 클릭할 때 호출됩니다. 브라우저의dblclickevent에 해당합니다. -
onDoubleClickCapture: A version ofonDoubleClickthat fires in the capture phase.onDoubleClickCapture: 캡쳐 단계에서 실행되는 버전의onDoubleClick입니다. -
onDrag: ADragEventhandler function. Fires while the user is dragging something.onDrag:DragEvent핸들러 함수. 사용자가 무언가를 드래그하는 동안 호출됩니다. -
onDragCapture: A version ofonDragthat fires in the capture phase.onDragCapture: 캡쳐 단계에서 실행되는 버전의onDrag입니다. -
onDragEnd: ADragEventhandler function. Fires when the user stops dragging something.onDragEnd:DragEvent핸들러 함수. 사용자가 드래그를 멈출 때 호춣됩니다. -
onDragEndCapture: A version ofonDragEndthat fires in the capture phase.onDragEndCapture: 캡쳐 단계에서 실행되는 버전의onDragEnd입니다. -
onDragEnter: ADragEventhandler function. Fires when the dragged content enters a valid drop target.onDragEnter: ADragEvent핸들러 함수. 드래그중인 컨텐트가 유효한 드롭 대상에 진입시 호출됩니다. -
onDragEnterCapture: A version ofonDragEnterthat fires in the capture phase.onDragEnterCapture: 캡쳐 단계에서 실행되는 버전의onDragEnter입니다. -
onDragOver: ADragEventhandler function. Fires on a valid drop target while the dragged content is dragged over it. You must calle.preventDefault()here to allow dropping.onDragOver:DragEvent핸들러 함수. 컨텐트가 유효한 드롭 대상 위에서 드래그중인 동안 호출됩니다. 드롭을 허용하려면e.preventDefault()를 호출해야 합니다. -
onDragOverCapture: A version ofonDragOverthat fires in the capture phase.onDragOverCapture: 캡쳐 단계에서 실행되는 버전의onDragOver입니다. -
onDragStart: ADragEventhandler function. Fires when the user starts dragging an element.onDragStart:DragEvent핸들러 함수. 사용자가 엘리먼트를 드래그하기 시작할 때 호출됩니다. -
onDragStartCapture: A version ofonDragStartthat fires in the capture phase.onDragStartCapture: 캡쳐 단계에서 실행되는 버전의onDragStart입니다. -
onDrop: ADragEventhandler function. Fires when something is dropped on a valid drop target.onDrop:DragEvent핸들러 함수. 유효한 드롭 대상에 드롭할 때 호출됩니다. -
onDropCapture: A version ofonDropthat fires in the capture phase.onDropCapture: 캡쳐 단계에서 실행되는 버전의onDrop입니다. -
onFocus: AFocusEventhandler function. Fires when an element receives focus. Unlike the built-in browserfocusevent, in React theonFocusevent bubbles.onFocus:FocusEvent핸들러 함수. 엘리먼트가 포커스될 때 호출됩니다. 브라우저 빌트인focus와 달리, React의onFocus이벤트는 버블이 발생합니다. -
onFocusCapture: A version ofonFocusthat fires in the capture phase.onFocusCapture: 캡쳐 단계에서 실행되는 버전의onFocus입니다. -
onGotPointerCapture: APointerEventhandler function. Fires when an element programmatically captures a pointer.onGotPointerCapture:PointerEvent핸들러 함수. 엘리먼트가 프로그램적으로 포인터를 캡쳐할 때 호출됩니다. -
onGotPointerCaptureCapture: A version ofonGotPointerCapturethat fires in the capture phase.onGotPointerCaptureCapture: 캡쳐 단계에서 실행되는 버전의onGotPointerCapture입니다. -
onKeyDown: AKeyboardEventhandler function. Fires when a key is pressed.onKeyDown:KeyboardEvent핸들러 함수. 키가 눌릴 때 호출됩니다. -
onKeyDownCapture: A version ofonKeyDownthat fires in the capture phase.onKeyDownCapture: 캡쳐 단계에서 실행되는 버전의onKeyDown입니다. -
onKeyPress: AKeyboardEventhandler function. Deprecated. UseonKeyDownoronBeforeInputinstead.onKeyPress:KeyboardEvent핸들러 함수. 지원중단되었습니다.onKeyDown또는onBeforeInput를 대신 사용하세요. -
onKeyPressCapture: A version ofonKeyPressthat fires in the capture phase.onKeyPressCapture: 캡쳐 단계에서 실행되는 버전의onKeyPress입니다. -
onKeyUp: AKeyboardEventhandler function. Fires when a key is released.onKeyUp:KeyboardEvent핸들러 함수. 키를 놓을 때 호출됩니다. -
onKeyUpCapture: A version ofonKeyUpthat fires in the capture phase.onKeyUpCapture: 캡쳐 단계에서 실행되는 버전의onKeyUp입니다. -
onLostPointerCapture: APointerEventhandler function. Fires when an element stops capturing a pointer.onLostPointerCapture:PointerEvent핸들러 함수. 엘리먼트가 포인터 캡쳐를 중지할 때 호출됩니다. -
onLostPointerCaptureCapture: A version ofonLostPointerCapturethat fires in the capture phase.onLostPointerCaptureCapture: 캡쳐 단계에서 실행되는 버전의onLostPointerCapture입니다. -
onMouseDown: AMouseEventhandler function. Fires when the pointer is pressed down.onMouseDown:MouseEvent핸들러 함수. 포인터를 누를 때 호출됩니다. -
onMouseDownCapture: A version ofonMouseDownthat fires in the capture phase.onMouseDownCapture: 캡쳐 단계에서 실행되는 버전의onMouseDown입니다. -
onMouseEnter: AMouseEventhandler function. Fires when the pointer moves inside an element. Does not have a capture phase. Instead,onMouseLeaveandonMouseEnterpropagate from the element being left to the one being entered.onMouseEnter:MouseEvent핸들러 함수. 포인터가 엘리먼트 내부로 이동할 때 호출됩니다. 캡쳐 단계가 없습니다. 대신onMouseLeave와onMouseEnter는 떠나는 엘리먼트에서 들어가는 이벤트로 전파됩니다. -
onMouseLeave: AMouseEventhandler function. Fires when the pointer moves outside an element. Does not have a capture phase. Instead,onMouseLeaveandonMouseEnterpropagate from the element being left to the one being entered.onMouseLeave:MouseEvent핸들러 함수. 포인터가 엘리먼트 외부로 이동할 때 호출됩니다. 캡쳐 단계가 없습니다. 대신onMouseLeave및onMouseEnter는 떠나는 엘리먼트에서 들어가는 엘리먼트로 전파됩니다. -
onMouseMove: AMouseEventhandler function. Fires when the pointer changes coordinates.onMouseMove:MouseEvent핸들러 함수. 포인터 좌표가 변경될 때 호출됩니다. -
onMouseMoveCapture: A version ofonMouseMovethat fires in the capture phase.onMouseMoveCapture: 캡쳐 단계에서 실행되는 버전의onMouseMove입니다. -
onMouseOut: AMouseEventhandler function. Fires when the pointer moves outside an element, or if it moves into a child element.onMouseOut:MouseEvent핸들러 함수. 포인터가 엘리먼트 바깥으로 또는 자식 엘리먼트로 이동할 때 호출됩니다. -
onMouseOutCapture: A version ofonMouseOutthat fires in the capture phase.onMouseOutCapture: 캡쳐 단계에서 실행되는 버전의onMouseOut입니다. -
onMouseUp: AMouseEventhandler function. Fires when the pointer is released.onMouseUp:MouseEvent핸들러 함수. 포인터를 놓을 때 호출됩니다. -
onMouseUpCapture: A version ofonMouseUpthat fires in the capture phase.onMouseUpCapture: 캡쳐 단계에서 실행되는 버전의onMouseUp입니다. -
onPointerCancel: APointerEventhandler function. Fires when the browser cancels a pointer interaction.onPointerCancel:PointerEvent핸들러 함수. 브라우저가 포인터 상호작용을 취소할 때 호출됩니다. -
onPointerCancelCapture: A version ofonPointerCancelthat fires in the capture phase.onPointerCancelCapture: 캡쳐 단계에서 실행되는 버전의onPointerCancel입니다. -
onPointerDown: APointerEventhandler function. Fires when a pointer becomes active.onPointerDown:PointerEvent핸들러 함수. 포인터가 활성화될 때 호출됩니다. -
onPointerDownCapture: A version ofonPointerDownthat fires in the capture phase.onPointerDownCapture: 캡쳐 단계에서 실행되는 버전의onPointerDown입니다. -
onPointerEnter: APointerEventhandler function. Fires when a pointer moves inside an element. Does not have a capture phase. Instead,onPointerLeaveandonPointerEnterpropagate from the element being left to the one being entered.onPointerEnter:PointerEvent핸들러 함수. 포인터가 내부 엘리먼트로 이동할 때 호출됩니다. 캡쳐 단계가 없습니다. 대신onPointerLeave및onPointerEnter는 떠나는 엘리먼트에서 들어가는 엘리먼트로 전파됩니다. -
onPointerLeave: APointerEventhandler function. Fires when a pointer moves outside an element. Does not have a capture phase. Instead,onPointerLeaveandonPointerEnterpropagate from the element being left to the one being entered.onPointerLeave:PointerEvent핸들러 함수. 포인터가 엘리먼트 외부로 이동할 때 호출됩니다. 캡쳐 단계가 없습니다. 대신onPointerLeave및onPointerEnter는 떠나는 엘리먼트에서 들어가는 엘리먼트로 전파됩니다. -
onPointerMove: APointerEventhandler function. Fires when a pointer changes coordinates.onPointerMove:PointerEvent핸들러 함수. 포인터 좌표가 변경될 때 호출됩니다. -
onPointerMoveCapture: A version ofonPointerMovethat fires in the capture phase.onPointerMoveCapture: 캡쳐 단계에서 실행되는 버전의onPointerMove입니다. -
onPointerOut: APointerEventhandler function. Fires when a pointer moves outside an element, if the pointer interaction is cancelled, and a few other reasons.onPointerOut:PointerEvent핸들러 함수. 포인터가 엘리먼트 외부로 이동하거나, 포인터 상호작용이 취소되거나, 기타 몇몇 다른 이유들로 호출됩니다. -
onPointerOutCapture: A version ofonPointerOutthat fires in the capture phase.onPointerOutCapture: 캡쳐 단계에서 실행되는 버전의onPointerOut입니다. -
onPointerUp: APointerEventhandler function. Fires when a pointer is no longer active.onPointerUp:PointerEvent핸들러 함수. 포인터가 비활성화될 때 호출됩니다. -
onPointerUpCapture: A version ofonPointerUpthat fires in the capture phase.onPointerUpCapture: 캡쳐 단계에서 실행되는 버전의onPointerUp입니다. -
onPaste: AClipboardEventhandler function. Fires when the user tries to paste something from the clipboard.onPaste:ClipboardEvent핸들러 함수. 사용자가 클립보드로부터 무언가를 붙여넣고자 할 때 호출됩니다. -
onPasteCapture: A version ofonPastethat fires in the capture phase.onPasteCapture: 캡쳐 단계에서 실행되는 버전의onPaste입니다. -
onScroll: AnEventhandler function. Fires when an element has been scrolled. This event does not bubble.onScroll:Event핸들러 함수. 엘리먼트가 스크롤될 때 호출됩니다. 이 이벤트는 버블이 발생하지 않습니다. -
onScrollCapture: A version ofonScrollthat fires in the capture phase.onScrollCapture: 캡쳐 단계에서 실행되는 버전의onScroll입니다. -
onSelect: AnEventhandler function. Fires after the selection inside an editable element like an input changes. React extends theonSelectevent to work forcontentEditable={true}elements as well. In addition, React extends it to fire for empty selection and on edits (which may affect the selection).onSelect:Event핸들러 함수. input과 같은 편집 가능한 엘리먼트 내부의 선택영역이 변경될 때 호출됩니다. React는onSelect이벤트를contentEditable={true}엘리먼트에서도 작동하도록 확장합니다. 또한 선택 영역이 빈 경우 및 선택에 영향을 줄 수 있는 편집 시에도 발동되도록 확장합니다. -
onSelectCapture: A version ofonSelectthat fires in the capture phase.onSelectCapture: 캡쳐 단계에서 실행되는 버전의onSelect입니다. -
onTouchCancel: ATouchEventhandler function. Fires when the browser cancels a touch interaction.onTouchCancel:TouchEvent핸들러 함수. 브라우저가 터치 상호작용을 취소할 때 호출됩니다. -
onTouchCancelCapture: A version ofonTouchCancelthat fires in the capture phase.onTouchCancelCapture: 캡쳐 단계에서 실행되는 버전의onTouchCancel입니다. -
onTouchEnd: ATouchEventhandler function. Fires when one or more touch points are removed.onTouchEnd:TouchEvent핸들러 함수. 하나 이상의 터치 포인트가 제거될 때 호출됩니다. -
onTouchEndCapture: A version ofonTouchEndthat fires in the capture phase.onTouchEndCapture: 캡쳐 단계에서 실행되는 버전의onTouchEnd입니다. -
onTouchMove: ATouchEventhandler function. Fires one or more touch points are moved.onTouchMove:TouchEvent핸들러 함수. 하나 이상의 터치 포인트가 이동할 때 호출됩니다. -
onTouchMoveCapture: A version ofonTouchMovethat fires in the capture phase.onTouchMoveCapture: 캡쳐 단계에서 실행되는 버전의onTouchMove입니다. -
onTouchStart: ATouchEventhandler function. Fires when one or more touch points are placed.onTouchStart:TouchEvent핸들러 함수. 하나 이상의 터치 포인트가 배치될 때 호출됩니다. -
onTouchStartCapture: A version ofonTouchStartthat fires in the capture phase.onTouchStartCapture: 캡쳐 단계에서 실행되는 버전의onTouchStart입니다. -
onTransitionEnd: ATransitionEventhandler function. Fires when a CSS transition completes.onTransitionEnd:TransitionEvent핸들러 함수. CSS 트랜지션 종료시 호출됩니다. -
onTransitionEndCapture: A version ofonTransitionEndthat fires in the capture phase.onTransitionEndCapture: 캡쳐 단계에서 실행되는 버전의onTransitionEnd입니다. -
onWheel: AWheelEventhandler function. Fires when the user rotates a wheel button.onWheel:WheelEvent핸들러 함수. 사용자가 휠 버튼을 돌릴 때 호출됩니다. -
onWheelCapture: A version ofonWheelthat fires in the capture phase.onWheelCapture: 캡쳐 단계에서 실행되는 버전의onWheel입니다. -
role: A string. Specifies the element role explicitly for assistive technologies.role: 문자열. 보조기술에 대한 엘리먼트의 역할을 명시적으로 지정합니다. -
slot: A string. Specifies the slot name when using shadow DOM. In React, an equivalent pattern is typically achieved by passing JSX as props, for example<Layout left={<Sidebar />} right={<Content />} />.slot: 문자열. 새도우 DOM을 사용할 때 슬롯의 이름을 지정합니다. React에서는 일반적으로 JSX를 props로 전달함으로써 동등한 패턴을 얻을 수 있습니다 (예:<Layout left={<Sidebar />} right={<Content />} />). -
spellCheck: A boolean or null. If explicitly set totrueorfalse, enables or disables spellchecking.spellCheck: 불리언 또는 null. 명시적으로true또는false로 설정된 경우 맞춤법 검사를 활성화 또는 비활성화합니다. -
tabIndex: A number. Overrides the default Tab button behavior. Avoid using values other than-1and0.tabIndex: 숫자. 기본 탭버튼 동작을 재정의합니다.-1및0이외의 값을 사용하지 마세요. -
title: A string. Specifies the tooltip text for the element.title: 문자열. 엘리먼트의 툴팁 텍스트를 지정합니다. -
translate: Either'yes'or'no'. Passing'no'excludes the element content from being translated.translate:'yes'또는'no'중 하나입니다.'no'를 전달하면 엘리먼트의 콘텐츠가 번역에서 제외됩니다.
You can also pass custom attributes as props, for example mycustomprop="someValue". This can be useful when integrating with third-party libraries. The custom attribute name must be lowercase and must not start with on. The value will be converted to a string. If you pass null or undefined, the custom attribute will be removed.
사용자 정의 속성을 프로퍼티로 전달할 수도 있습니다(예: mycustomprop="someValue"). 이는 타사 라이브러리와 통합할 때 유용할 수 있습니다. 사용자 정의 속성 이름은 소문자여야 하며 on으로 시작하지 않아야 합니다. 값은 문자열로 변환됩니다. null 또는 undefined를 전달하면 사용자 정의 속성이 제거됩니다.
These events fire only for the <form> elements:
다음 이벤트들은 <form> 엘리먼트에 대해서만 호출됩니다:
-
onReset: AnEventhandler function. Fires when a form gets reset.onReset:Event핸들러 함수. 폼을 리셋할 때 호출됩니다. -
onResetCapture: A version ofonResetthat fires in the capture phase.onResetCapture: 캡쳐 단계에서 실행되는 버전의onReset입니다. -
onSubmit: AnEventhandler function. Fires when a form gets submitted.onSubmit:Event핸들러 함수. 폼을 제출할 때 호출됩니다. -
onSubmitCapture: A version ofonSubmitthat fires in the capture phase.onSubmitCapture: 캡쳐 단계에서 실행되는 버전의onSubmit입니다.
These events fire only for the <dialog> elements. Unlike browser events, they bubble in React:
다음 이벤트들은 <dialog> 엘리먼트에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:
-
onCancel: AnEventhandler function. Fires when the user tries to dismiss the dialog.onCancel:Event핸들러 함수. 사용자가 dialog를 닫으려 할 때 호출됩니다. -
onCancelCapture: A version ofonCancelthat fires in the capture phase.onCancelCapture: 캡쳐 단계에서 실행되는 버전의onCancel입니다. -
onClose: AnEventhandler function. Fires when a dialog has been closed.onClose:Event핸들러 함수. dialog가 닫혔을 때 호출됩니다. -
onCloseCapture: A version ofonClosethat fires in the capture phase.onCloseCapture: 캡쳐 단계에서 실행되는 버전의onClose입니다.
These events fire only for the <details> elements. Unlike browser events, they bubble in React:
다음 이벤트들은 <details> 엘리먼트에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:
-
onToggle: AnEventhandler function. Fires when the user toggles the details.onToggle:Event핸들러 함수. 사용자가 details를 토글할 때 호출됩니다. -
onToggleCapture: A version ofonTogglethat fires in the capture phase.onToggleCapture: 캡쳐 단계에서 실행되는 버전의onToggle입니다.
These events fire for <img>, <iframe>, <object>, <embed>, <link>, and SVG <image> elements. Unlike browser events, they bubble in React:
다음 이벤트들은 <img>, <iframe>, <object>, <embed>, <link>, SVG <image> 엘리먼트에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:
-
onLoad: AnEventhandler function. Fires when the resource has loaded.onLoad:Event핸들러 함수. 리소스가 로드되면 호출됩니다. -
onLoadCapture: A version ofonLoadthat fires in the capture phase.onLoadCapture: 캡쳐 단계에서 실행되는 버전의onLoad입니다. -
onError: AnEventhandler function. Fires when the resource could not be loaded.onError:Event핸들러 함수. 리소스를 로드할 수 없을 때 호출됩니다. -
onErrorCapture: A version ofonErrorthat fires in the capture phase.onErrorCapture: 캡쳐 단계에서 실행되는 버전의onError입니다.
These events fire for resources like <audio> and <video>. Unlike browser events, they bubble in React:
다음 이벤트들은 <audio>나 <video> 같은 리소스에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:
-
onAbort: AnEventhandler function. Fires when the resource has not fully loaded, but not due to an error.onAbort:Event핸들러 함수. 리소스가 완전히 로드되지 않았지만 오류로 인한 것이 아닌 경우 호출됩니다. -
onAbortCapture: A version ofonAbortthat fires in the capture phase.onAbortCapture: 캡쳐 단계에서 실행되는 버전의onAbort입니다. -
onCanPlay: AnEventhandler function. Fires when there’s enough data to start playing, but not enough to play to the end without buffering.onCanPlay:Event핸들러 함수. 재생하기에 충분한 데이터가 있지만 버퍼링 없이 끝까지 재생할 수는 없을 때 호출됩니다. -
onCanPlayCapture: A version ofonCanPlaythat fires in the capture phase.onCanPlayCapture: 캡쳐 단계에서 실행되는 버전의onCanPlay입니다. -
onCanPlayThrough: AnEventhandler function. Fires when there’s enough data that it’s likely possible to start playing without buffering until the end.onCanPlayThrough:Event핸들러 함수. 데이터가 충분하여 끝까지 버퍼링 없이 재생할 수 있을 때 호출됩니다. -
onCanPlayThroughCapture: A version ofonCanPlayThroughthat fires in the capture phase.onCanPlayThroughCapture: 캡쳐 단계에서 실행되는 버전의onCanPlayThrough입니다. -
onDurationChange: AnEventhandler function. Fires when the media duration has updated.onDurationChange:Event핸들러 함수. 미디어 지속시간이 업데이트될 때 호출됩니다. -
onDurationChangeCapture: A version ofonDurationChangethat fires in the capture phase.onDurationChangeCapture: 캡쳐 단계에서 실행되는 버전의onDurationChange입니다. -
onEmptied: AnEventhandler function. Fires when the media has become empty.onEmptied:Event핸들러 함수. 미디어가 비었을 때 호출됩니다. -
onEmptiedCapture: A version ofonEmptiedthat fires in the capture phase.onEmptiedCapture: 캡쳐 단계에서 실행되는 버전의onEmptied입니다. -
onEncrypted: AnEventhandler function. Fires when the browser encounters encrypted media.onEncrypted:Event핸들러 함수. 브라우저에서 암호화된 미디어를 발견하면 호출됩니다. -
onEncryptedCapture: A version ofonEncryptedthat fires in the capture phase.onEncryptedCapture: 캡쳐 단계에서 실행되는 버전의onEncrypted입니다. -
onEnded: AnEventhandler function. Fires when the playback stops because there’s nothing left to play.onEnded:Event핸들러 함수. 재생할 콘텐츠가 남아 있지 않아 재생이 중지될 때 호출됩니다. -
onEndedCapture: A version ofonEndedthat fires in the capture phase.onEndedCapture: 캡쳐 단계에서 실행되는 버전의onEnded입니다. -
onError: AnEventhandler function. Fires when the resource could not be loaded.onError:Event핸들러 함수. 리소스를 로드할 수 없을 때 호출됩니다. -
onErrorCapture: A version ofonErrorthat fires in the capture phase.onErrorCapture: 캡쳐 단계에서 실행되는 버전의onError입니다. -
onLoadedData: AnEventhandler function. Fires when the current playback frame has loaded.onLoadedData:Event핸들러 함수. 현재 재생 프레임이 로드되면 호출됩니다. -
onLoadedDataCapture: A version ofonLoadedDatathat fires in the capture phase.onLoadedDataCapture: 캡쳐 단계에서 실행되는 버전의onLoadedData입니다. -
onLoadedMetadata: AnEventhandler function. Fires when metadata has loaded.onLoadedMetadata:Event핸들러 함수. 메타데이터가 로드되면 호출됩니다. -
onLoadedMetadataCapture: A version ofonLoadedMetadatathat fires in the capture phase.onLoadedMetadataCapture: 캡쳐 단계에서 실행되는 버전의onLoadedMetadata입니다. -
onLoadStart: AnEventhandler function. Fires when the browser started loading the resource.onLoadStart:Event핸들러 함수. 브라우저가 리소스 로드를 시작했을 때 호출됩니다. -
onLoadStartCapture: A version ofonLoadStartthat fires in the capture phase.onLoadStartCapture: 캡쳐 단계에서 실행되는 버전의onLoadStart입니다. -
onPause: AnEventhandler function. Fires when the media was paused.onPause:Event핸들러 함수. 미디어가 일시정지되었을 때 호출됩니다. -
onPauseCapture: A version ofonPausethat fires in the capture phase.onPauseCapture: 캡쳐 단계에서 실행되는 버전의onPause입니다. -
onPlay: AnEventhandler function. Fires when the media is no longer paused.onPlay:Event핸들러 함수. 미디어가 더이상 일시정지되지 않을 때 호출됩니다. -
onPlayCapture: A version ofonPlaythat fires in the capture phase.onPlayCapture: 캡쳐 단계에서 실행되는 버전의onPlay입니다. -
onPlaying: AnEventhandler function. Fires when the media starts or restarts playing.onPlaying:Event핸들러 함수. 미디어가 재생을 시작하거나 재시작할 때 호출됩니다. -
onPlayingCapture: A version ofonPlayingthat fires in the capture phase.onPlayingCapture: 캡쳐 단계에서 실행되는 버전의onPlaying입니다. -
onProgress: AnEventhandler function. Fires periodically while the resource is loading.onProgress:Event핸들러 함수. 리소스가 로드되는 동안 주기적으로 실행됩니다. -
onProgressCapture: A version ofonProgressthat fires in the capture phase.onProgressCapture: 캡쳐 단계에서 실행되는 버전의onProgress입니다. -
onRateChange: AnEventhandler function. Fires when playback rate changes.onRateChange:Event핸들러 함수. 재생 속도가 변경되면 호출됩니다. -
onRateChangeCapture: A version ofonRateChangethat fires in the capture phase.onRateChangeCapture: 캡쳐 단계에서 실행되는 버전의onRateChange입니다. -
onResize: AnEventhandler function. Fires when video changes size.onResize:Event핸들러 함수. 동영상 크기가 변경될 때 호출됩니다. -
onResizeCapture: A version ofonResizethat fires in the capture phase.onResizeCapture: 캡쳐 단계에서 실행되는 버전의onResize입니다. -
onSeeked: AnEventhandler function. Fires when a seek operation completes.onSeeked:Event핸들러 함수. 탐색 작업이 완료되면 호출됩니다. -
onSeekedCapture: A version ofonSeekedthat fires in the capture phase.onSeekedCapture: 캡쳐 단계에서 실행되는 버전의onSeeked입니다. -
onSeeking: AnEventhandler function. Fires when a seek operation starts.onSeeking:Event핸들러 함수. 탐색 작업 시작시 호출됩니다. -
onSeekingCapture: A version ofonSeekingthat fires in the capture phase.onSeekingCapture: 캡쳐 단계에서 실행되는 버전의onSeeking입니다. -
onStalled: AnEventhandler function. Fires when the browser is waiting for data but it keeps not loading.onStalled:Event핸들러 함수. 브라우저가 데이터를 대기 중이지만 계속 로드되지 않을 때 호출됩니다. -
onStalledCapture: A version ofonStalledthat fires in the capture phase.onStalledCapture: 캡쳐 단계에서 실행되는 버전의onStalled입니다. -
onSuspend: AnEventhandler function. Fires when loading the resource was suspended.onSuspend:Event핸들러 함수. 리소스 로딩이 일시 중단되었을 때 호출됩니다. -
onSuspendCapture: A version ofonSuspendthat fires in the capture phase.onSuspendCapture: 캡쳐 단계에서 실행되는 버전의onSuspend입니다. -
onTimeUpdate: AnEventhandler function. Fires when the current playback time updates.onTimeUpdate:Event핸들러 함수. 현재 재생 시간이 업데이트될 때 호출됩니다. -
onTimeUpdateCapture: A version ofonTimeUpdatethat fires in the capture phase.onTimeUpdateCapture: 캡쳐 단계에서 실행되는 버전의onTimeUpdate입니다. -
onVolumeChange: AnEventhandler function. Fires when the volume has changed.onVolumeChange:Event핸들러 함수. 볼륨이 변경되었을 때 호출됩니다. -
onVolumeChangeCapture: A version ofonVolumeChangethat fires in the capture phase.onVolumeChangeCapture: 캡쳐 단계에서 실행되는 버전의onVolumeChange입니다. -
onWaiting: AnEventhandler function. Fires when the playback stopped due to temporary lack of data.onWaiting:Event핸들러 함수. 일시적인 데이터 부족으로 재생이 중지된 경우 호출됩니다. -
onWaitingCapture: A version ofonWaitingthat fires in the capture phase.onWaitingCapture: 캡쳐 단계에서 실행되는 버전의onWaiting입니다.
Caveats주의사항
-
You cannot pass both
childrenanddangerouslySetInnerHTMLat the same time.children과dangerouslySetInnerHTML을 동시에 전달할 수 없습니다. -
Some events (like
onAbortandonLoad) don’t bubble in the browser, but bubble in React. 일부 이벤트(예:onAbort및onLoad)는 브라우저에서는 버블링되지 않지만 React에서는 버블링됩니다.
ref callback function ref 콜백 함수
Instead of a ref object (like the one returned by useRef), you may pass a function to the ref attribute.
ref 객체(예: useRef에서 반환하는 객체) 대신 ref 속성에 함수를 전달할 수 있습니다.
<div ref={(node) => console.log(node)} />See an example of using the ref callback.
ref 콜백 사용 예시를 확인하세요.
When the <div> DOM node is added to the screen, React will call your ref callback with the DOM node as the argument. When that <div> DOM node is removed, React will call your ref callback with null.
<div> DOM 노드가 화면에 추가되면 React는 DOM node를 인수로 사용하여 ref 콜백을 호출합니다. 해당 <div> DOM 노드가 제거되면 React는 null로 ref 콜백을 호출합니다.
React will also call your ref callback whenever you pass a different ref callback. In the above example, (node) => { ... } is a different function on every render. When your component re-renders, the previous function will be called with null as the argument, and the next function will be called with the DOM node.
React는 또한 다른 ref 콜백을 전달할 때마다 ref 콜백을 호출합니다. 위의 예에서 (node) => { ... }는 렌더링할 때마다 다른 기능입니다. 이것이 컴포넌트가 다시 렌더링될 때 null을 인자로 사용하여 previous 함수가 호출되고 DOM 노드로 next 함수가 호출되는 이유입니다.
Parameters매개변수
node: A DOM node ornull. React will pass you the DOM node when the ref gets attached, andnullwhen the ref gets detached. Unless you pass the same function reference for therefcallback on every render, the callback will get temporarily detached and re-attached during every re-render of the component.node: DOM 노드 또는null. React는 ref가 연결될 때 DOM 노드를 전달하고, ref가 분리될 때null을 전달합니다. 모든 렌더링에서ref콜백에 대해 동일한 함수 참조를 전달하지 않는 한, 컴포넌트를 다시 렌더링할 때마다 콜백이 일시적으로 분리되었다가 다시 연결됩니다.
Returns반환값
Do not return anything from the ref callback.
ref 콜백에서 아무것도 반환하지 않습니다.
React event object React 이벤트 객체
Your event handlers will receive a React event object. It is also sometimes known as a “synthetic event”. 이벤트 핸들러는 React 이벤트 객체를 받게 되며, “합성 이벤트”라고도 합니다.
<button onClick={e => {
console.log(e); // React event object
// React 이벤트 객체
}} />It conforms to the same standard as the underlying DOM events, but fixes some browser inconsistencies. 기본 DOM 이벤트와 동일한 표준을 준수하지만 일부 브라우저 간의 불일치를 수정합니다.
Some React events do not map directly to the browser’s native events. For example in onMouseLeave, e.nativeEvent will point to a mouseout event. The specific mapping is not part of the public API and may change in the future. If you need the underlying browser event for some reason, read it from e.nativeEvent.
일부 React 이벤트는 브라우저의 네이티브 이벤트에 직접 매핑되지 않습니다. 예를 들어, onMouseLeave에서 e.nativeEvent는 mouseout 이벤트를 가리킵니다. 특정 매핑은 공개 API의 일부가 아니며 향후 변경될 수 있습니다. 어떤 이유로 기본 브라우저 이벤트가 필요한 경우 e.nativeEvent에서 읽어오세요.
Properties 프로퍼티
React event objects implement some of the standard Event properties:
React 이벤트 객체는 표준 Event 프로퍼티 중 일부를 구현합니다:
-
bubbles: A boolean. Returns whether the event bubbles through the DOM.bubbles: 불리언. 이벤트가 DOM을 통해 버블을 발생시킬지 여부를 반환합니다. -
cancelable: A boolean. Returns whether the event can be canceled.cancelable: 불리언. 이벤트를 취소할 수 있는지 여부를 반환합니다. -
currentTarget: A DOM node. Returns the node to which the current handler is attached in the React tree.currentTarget: DOM 노드. React 트리에서 현재 핸들러가 연결된 노드를 반환합니다. -
defaultPrevented: A boolean. Returns whetherpreventDefaultwas called.defaultPrevented: 불리언. preventDefault`가 호출되었는지 여부를 반환합니다. -
eventPhase: A number. Returns which phase the event is currently in.eventPhase: 숫자. 이벤트가 현재 어떤 단계에 있는지 반환합니다. -
isTrusted: A boolean. Returns whether the event was initiated by user.isTrusted: 불리언. 이벤트가 사용자에 의해 시작되었는지 여부를 반환합니다. -
target: A DOM node. Returns the node on which the event has occurred (which could be a distant child).target: DOM 노드. 이벤트가 발생한 노드(먼 자식일 수 있음)를 반환합니다. -
timeStamp: A number. Returns the time when the event occurred.timeStamp: 숫자. 이벤트가 발생한 시간을 반환합니다.
Additionally, React event objects provide these properties: 또한 React 이벤트 객체는 이러한 프로퍼티를 제공합니다:
nativeEvent: A DOMEvent. The original browser event object.nativeEvent: DOMEvent. 원본 브라우저 이벤트 객체입니다.
Methods 메서드
React event objects implement some of the standard Event methods:
React 이벤트 객체는 표준 Event 메서드 중 일부를 구현합니다:
-
preventDefault(): Prevents the default browser action for the event.preventDefault(): 이벤트에 대한 기본 브라우저 액션을 방지합니다. -
stopPropagation(): Stops the event propagation through the React tree.stopPropagation(): React 트리를 통한 이벤트 전파를 중지합니다.
Additionally, React event objects provide these methods: 또한 React 이벤트 객체는 이러한 메서드를 제공합니다:
-
isDefaultPrevented(): Returns a boolean value indicating whetherpreventDefaultwas called.isDefaultPrevented():preventDefault가 호출되었는지 여부를 나타내는 불리언 값을 반환합니다. -
isPropagationStopped(): Returns a boolean value indicating whetherstopPropagationwas called.isPropagationStopped():stopPropagation가 호출되었는지 여부를 나타내는 불리언 값을 반환합니다. -
persist(): Not used with React DOM. With React Native, call this to read event’s properties after the event.persist(): React DOM에서는 사용되지 않습니다. React Native에서는 이벤트 이후 이벤트의 프로퍼티를 읽으려면 이 함수를 호출합니다. -
isPersistent(): Not used with React DOM. With React Native, returns whetherpersisthas been called.isPersistent(): React DOM에서는 사용되지 않습니다. React Native에서는persist가 호출되었는지 여부를 반환합니다.
Caveats주의사항
- The values of
currentTarget,eventPhase,target, andtypereflect the values your React code expects. Under the hood, React attaches event handlers at the root, but this is not reflected in React event objects. For example,e.currentTargetmay not be the same as the underlyinge.nativeEvent.currentTarget. For polyfilled events,e.type(React event type) may differ frome.nativeEvent.type(underlying type).currentTarget,eventPhase,target,type의 값은 React 코드가 기대하는 값을 반영합니다. 내부적으로 React는 이벤트 핸들러를 루트에 첨부하지만, 이는 React 이벤트 객체에는 반영되지 않습니다. 예를 들어,e.currentTarget은 기본e.nativeEvent.currentTarget과 같지 않을 수 있습니다. 폴리필 이벤트의 경우,e.type(React 이벤트 타입)이e.nativeEvent.type(기본 타입)과 다를 수 있습니다.
AnimationEvent handler function AnimationEvent 핸들러 함수
An event handler type for the CSS animation events. CSS 애니메이션 이벤트에 대한 이벤트 핸들러 유형입니다.
<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>Parameters매개변수
-
e: A React event object with these extraAnimationEventproperties:e: 추가AnimationEvent속성을 가진 React 이벤트 객체입니다:
ClipboardEvent handler function ClipboardEvent 핸들러 함수
An event handler type for the Clipboard API events. Clipboard API 이벤트에 대한 이벤트 핸들러 유형입니다.
<input
onCopy={e => console.log('onCopy')}
onCut={e => console.log('onCut')}
onPaste={e => console.log('onPaste')}
/>Parameters매개변수
-
e: A React event object with these extraClipboardEventproperties:e: 추가ClipboardEvent속성을 가진 React 이벤트 객체입니다:
CompositionEvent handler function CompositionEvent 핸들러 함수
An event handler type for the input method editor (IME) events. input method editor (IME) 이벤트에 대한 이벤트 핸들러 유형입니다.
<input
onCompositionStart={e => console.log('onCompositionStart')}
onCompositionUpdate={e => console.log('onCompositionUpdate')}
onCompositionEnd={e => console.log('onCompositionEnd')}
/>Parameters매개변수
-
e: A React event object with these extraCompositionEventproperties:e: 추가CompositionEvent속성을 가진 React 이벤트 객체입니다:
DragEvent handler function DragEvent 핸들러 함수
An event handler type for the HTML Drag and Drop API events. HTML Drag and Drop API 이벤트에 대한 이벤트 핸들러 유형입니다.
<>
<div
draggable={true}
onDragStart={e => console.log('onDragStart')}
onDragEnd={e => console.log('onDragEnd')}
>
Drag source
</div>
<div
onDragEnter={e => console.log('onDragEnter')}
onDragLeave={e => console.log('onDragLeave')}
onDragOver={e => { e.preventDefault(); console.log('onDragOver'); }}
onDrop={e => console.log('onDrop')}
>
Drop target
</div>
</>Parameters매개변수
-
e: A React event object with these extraDragEventproperties:e: 추가DragEvent속성을 가진 React 이벤트 객체입니다:It also includes the inherited
MouseEventproperties: 상속된MouseEvent속성도 포함됩니다:altKeybuttonbuttonsctrlKeyclientXclientYgetModifierState(key)metaKeymovementXmovementYpageXpageYrelatedTargetscreenXscreenYshiftKey
It also includes the inherited
UIEventproperties: 상속된UIEvent속성도 포함됩니다:
FocusEvent handler function FocusEvent 핸들러 함수
An event handler type for the focus events. 포커스 이벤트에 대한 이벤트 핸들러 유형입니다.
<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>Parameters매개변수
-
e: A React event object with these extraFocusEventproperties:e: 추가FocusEvent속성을 가진 React 이벤트 객체입니다:It also includes the inherited
UIEventproperties: 상속된UIEvent속성도 포함됩니다:
Event handler function Event 핸들러 함수
An event handler type for generic events. 일반 이벤트를 위한 이벤트 핸들러 유형입니다.
Parameters매개변수
e: A React event object with no additional properties.
e: 추가 프로퍼티가 없는 React 이벤트 객체입니다.
InputEvent handler function InputEvent 핸들러 함수
An event handler type for the onBeforeInput event.
onBeforeInput 이벤트에 대한 이벤트 핸들러 유형입니다.
<input onBeforeInput={e => console.log('onBeforeInput')} />Parameters매개변수
-
e: A React event object with these extraInputEventproperties:e: 추가InputEvent프로퍼티가 있는 React 이벤트 객체입니다:
KeyboardEvent handler function KeyboardEvent 핸들러 함수
An event handler type for keyboard events. 키보드 이벤트를 위한 이벤트 핸들러 유형입니다.
<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>Parameters매개변수
-
e: A React event object with these extraKeyboardEventproperties:e: 추가KeyboardEvent속성을 가진 React 이벤트 객체입니다:altKeycharCodecodectrlKeygetModifierState(key)keykeyCodelocalemetaKeylocationrepeatshiftKeywhich
It also includes the inherited
UIEventproperties: 상속된UIEvent속성도 포함됩니다:
MouseEvent handler function MouseEvent 핸들러 함수
An event handler type for mouse events. 마우스 이벤트에 대한 이벤트 핸들러 유형입니다.
<div
onClick={e => console.log('onClick')}
onMouseEnter={e => console.log('onMouseEnter')}
onMouseOver={e => console.log('onMouseOver')}
onMouseDown={e => console.log('onMouseDown')}
onMouseUp={e => console.log('onMouseUp')}
onMouseLeave={e => console.log('onMouseLeave')}
/>Parameters매개변수
-
e: A React event object with these extraMouseEventproperties:e: 추가MouseEvent속성을 가진 React 이벤트 객체입니다:altKeybuttonbuttonsctrlKeyclientXclientYgetModifierState(key)metaKeymovementXmovementYpageXpageYrelatedTargetscreenXscreenYshiftKey
It also includes the inherited
UIEventproperties: 상속된UIEvent속성도 포함됩니다:
PointerEvent handler function PointerEvent 핸들러 함수
An event handler type for pointer events. 포인터 이벤트에 대한 이벤트 핸들러 유형입니다.
<div
onPointerEnter={e => console.log('onPointerEnter')}
onPointerMove={e => console.log('onPointerMove')}
onPointerDown={e => console.log('onPointerDown')}
onPointerUp={e => console.log('onPointerUp')}
onPointerLeave={e => console.log('onPointerLeave')}
/>Parameters매개변수
-
e: A React event object with these extraPointerEventproperties:e: 추가PointerEvent속성을 가진 React 이벤트 객체입니다:It also includes the inherited
MouseEventproperties: 상속된MouseEvent속성도 포함됩니다:altKeybuttonbuttonsctrlKeyclientXclientYgetModifierState(key)metaKeymovementXmovementYpageXpageYrelatedTargetscreenXscreenYshiftKey
It also includes the inherited
UIEventproperties: 상속된UIEvent속성도 포함됩니다:
TouchEvent handler function TouchEvent 핸들러 함수
An event handler type for touch events. 터치 이벤트에 대한 이벤트 핸들러 유형입니다.
<div
onTouchStart={e => console.log('onTouchStart')}
onTouchMove={e => console.log('onTouchMove')}
onTouchEnd={e => console.log('onTouchEnd')}
onTouchCancel={e => console.log('onTouchCancel')}
/>Parameters매개변수
-
e: A React event object with these extraTouchEventproperties:e: 추가TouchEvent속성을 가진 React 이벤트 객체입니다:It also includes the inherited
UIEventproperties: 상속된UIEvent속성도 포함됩니다:
TransitionEvent handler function TransitionEvent 핸들러 함수
An event handler type for the CSS transition events. CSS 트랜지션 이벤트에 대한 이벤트 핸들러 유형입니다.
<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>Parameters매개변수
-
e: A React event object with these extraTransitionEventproperties:e: 추가TransitionEvent속성을 가진 React 이벤트 객체입니다:
UIEvent handler function UIEvent 핸들러 함수
An event handler type for generic UI events. 일반 UI 이벤트를 위한 이벤트 핸들러 유형입니다.
<div
onScroll={e => console.log('onScroll')}
/>Parameters매개변수
-
e: A React event object with these extraUIEventproperties:e: 추가UIEvent속성을 가진 React 이벤트 객체입니다:
WheelEvent handler function WheelEvent 핸들러 함수
An event handler type for the onWheel event.
onWheel 이벤트에 대한 이벤트 핸들러 유형입니다.
<div
onWheel={e => console.log('onWheel')}
/>Parameters매개변수
-
e: A React event object with these extraWheelEventproperties:e: 추가WheelEvent속성을 가진 React 이벤트 객체입니다:It also includes the inherited
MouseEventproperties: 상속된MouseEvent속성도 포함됩니다:altKeybuttonbuttonsctrlKeyclientXclientYgetModifierState(key)metaKeymovementXmovementYpageXpageYrelatedTargetscreenXscreenYshiftKey
It also includes the inherited
UIEventproperties: 상속된UIEvent속성도 포함됩니다:
Usage사용법
Applying CSS styles CSS 스타일 적용하기
In React, you specify a CSS class with className. It works like the class attribute in HTML:
React에서는 className으로 CSS 클래스를 지정합니다. HTML의 class 속성처럼 작동합니다:
<img className="avatar" />Then you write the CSS rules for it in a separate CSS file: 그런 다음 별도의 CSS 파일에 해당 CSS 규칙을 작성합니다:
/* In your CSS */
.avatar {
border-radius: 50%;
}React does not prescribe how you add CSS files. In the simplest case, you’ll add a <link> tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.
React는 CSS 파일을 추가하는 방법을 규정하지 않습니다. 가장 간단한 경우 HTML에 <link> 태그를 추가하면 됩니다. 빌드 도구나 프레임워크를 사용하는 경우 해당 문서를 참조하여 프로젝트에 CSS 파일을 추가하는 방법을 알아보세요.
Sometimes, the style values depend on data. Use the style attribute to pass some styles dynamically:
때때로 스타일 값은 데이터에 따라 달라집니다. style 속성을 사용하여 일부 스타일을 동적으로 전달할 수 있습니다:
<img
className="avatar"
style={{
width: user.imageSize,
height: user.imageSize
}}
/>In the above example, style={{}} is not a special syntax, but a regular {} object inside the style={ } JSX curly braces. We recommend only using the style attribute when your styles depend on JavaScript variables.
위 예시에서 style={{}}은 특별한 구문이 아니라 style={ } JSX 중괄호 안에 있는 일반 {} 객체입니다. 스타일이 JavaScript 변수에 의존하는 경우에만 style 속성을 사용하는 것이 좋습니다.
export default function Avatar({ user }) { return ( <img src={user.imageUrl} alt={'Photo of ' + user.name} className="avatar" style={{ width: user.imageSize, height: user.imageSize }} /> ); }
Deep Dive | 심층 탐구
To apply CSS classes conditionally, you need to produce the className string yourself using JavaScript.
조건부로 CSS 클래스를 적용하려면 JavaScript를 사용하여 className 문자열을 직접 생성해야 합니다.
For example, className={'row ' + (isSelected ? 'selected': '')} will produce either className="row" or className="row selected" depending on whether isSelected is true.
예를 들어, className={'row ' + (isSelected ? 'selected': '')}는 isSelected가 true인지 여부에 따라 className="row" 또는 className="row selected"를 생성합니다.
To make this more readable, you can use a tiny helper library like classnames:
이를 더 읽기 쉽게 만들려면 classnames와 같은 작은 헬퍼 라이브러리를 사용할 수 있습니다:
import cn from 'classnames';
function Row({ isSelected }) {
return (
<div className={cn('row', isSelected && 'selected')}>
...
</div>
);
}It is especially convenient if you have multiple conditional classes: 조건부 클래스가 여러 개 있는 경우 특히 편리합니다:
import cn from 'classnames';
function Row({ isSelected, size }) {
return (
<div className={cn('row', {
selected: isSelected,
large: size === 'large',
small: size === 'small',
})}>
...
</div>
);
}Manipulating a DOM node with a ref ref로 DOM 노드 조작하기
Sometimes, you’ll need to get the browser DOM node associated with a tag in JSX. For example, if you want to focus an <input> when a button is clicked, you need to call focus() on the browser <input> DOM node.
때로는 JSX에서 태그와 연결된 브라우저 DOM 노드를 가져와야 할 수도 있습니다. 예를 들어, 버튼이 클릭될 때 <input>에 초점을 맞추려면 브라우저 <input> DOM 노드에서 focus()를 호출해야 합니다.
To obtain the browser DOM node for a tag, declare a ref and pass it as the ref attribute to that tag:
태그에 대한 브라우저 DOM 노드를 가져오려면 ref 선언하기를 통해 해당 태그에 ref 속성으로 전달합니다:
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
// ...
return (
<input ref={inputRef} />
// ...React will put the DOM node into inputRef.current after it’s been rendered to the screen.
React는 DOM 노드가 화면에 렌더링된 후 inputRef.current에 넣습니다.
import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }
Read more about manipulating DOM with refs and check out more examples. ref로 DOM 조작하기와 더 많은 예시를 확인해보세요.
For more advanced use cases, the ref attribute also accepts a callback function.
고급 사용 사례의 경우, ref 속성은 콜백 함수도 허용합니다.
Dangerously setting the inner HTML 내부 HTML을 위험하게 설정하는 경우
You can pass a raw HTML string to an element like so: 다음과 같이 원본 HTML 문자열을 요소에 전달할 수 있습니다:
const markup = { __html: '<p>some raw html</p>' };
return <div dangerouslySetInnerHTML={markup} />;This is dangerous. As with the underlying DOM innerHTML property, you must exercise extreme caution! Unless the markup is coming from a completely trusted source, it is trivial to introduce an XSS vulnerability this way.
이렇게 작성하는 것은 위험합니다. 기본 DOM innerHTML 속성과 마찬가지로 극도의 주의를 기울여야 합니다! 마크업이 완전히 신뢰할 수 있는 출처에서 제공되지 않는 한, 이런 식으로 XSS 취약점을 도입하는 것은 위험한 일입니다.
For example, if you use a Markdown library that converts Markdown to HTML, you trust that its parser doesn’t contain bugs, and the user only sees their own input, you can display the resulting HTML like this: 예를 들어, 마크다운을 HTML로 변환하는 마크다운 라이브러리를 사용하는 경우 해당 파서에 버그가 없고 사용자가 자신의 입력만 볼 수 있다고 믿는다면 다음과 같이 결과 HTML을 표시할 수 있습니다:
import { Remarkable } from 'remarkable'; const md = new Remarkable(); function renderMarkdownToHTML(markdown) { // This is ONLY safe because the output HTML // is shown to the same user, and because you // trust this Markdown parser to not have bugs. const renderedHTML = md.render(markdown); return {__html: renderedHTML}; } export default function MarkdownPreview({ markdown }) { const markup = renderMarkdownToHTML(markdown); return <div dangerouslySetInnerHTML={markup} />; }
The {__html} object should be created as close to where the HTML is generated as possible, like the above example does in the renderMarkdownToHTML function. This ensures that all raw HTML being used in your code is explicitly marked as such, and that only variables that you expect to contain HTML are passed to dangerouslySetInnerHTML. It is not recommended to create the object inline like <div dangerouslySetInnerHTML={{__html: markup}} />.
To see why rendering arbitrary HTML is dangerous, replace the code above with this: 임의의 HTML을 렌더링하는 것이 왜 위험한지 알아보려면 위의 코드를 다음과 같이 바꾸세요:
const post = {
// Imagine this content is stored in the database.
// 이 콘텐츠가 데이터베이스에 저장되어 있다고 가정해 보겠습니다.
content: `<img src="" onerror='alert("you were hacked")'>`
};
export default function MarkdownPreview() {
// 🔴 SECURITY HOLE: passing untrusted input to dangerouslySetInnerHTML
// 🔴 보안 허점: 신뢰할 수 없는 input을 위험하게 dangerouslySetInnerHTML로 전달합니다.
const markup = { __html: post.content };
return <div dangerouslySetInnerHTML={markup} />;
}The code embedded in the HTML will run. A hacker could use this security hole to steal user information or to perform actions on their behalf. Only use dangerouslySetInnerHTML with trusted and sanitized data.
HTML에 포함된 코드가 실행됩니다. 해커는 이 보안 허점을 이용해 사용자 정보를 훔치거나 사용자 대신 작업을 수행할 수 있습니다. 신뢰할 수 있는 위생 처리된 데이터에 대해서만 dangerouslySetInnerHTML를 사용하세요.
Handling mouse events 마우스 이벤트 처리하기
This example shows some common mouse events and when they fire. 이 예시는 몇 가지 일반적인 마우스 이벤트와 이벤트 발생 시점을 보여줍니다.
export default function MouseExample() { return ( <div onMouseEnter={e => console.log('onMouseEnter (parent)')} onMouseLeave={e => console.log('onMouseLeave (parent)')} > <button onClick={e => console.log('onClick (first button)')} onMouseDown={e => console.log('onMouseDown (first button)')} onMouseEnter={e => console.log('onMouseEnter (first button)')} onMouseLeave={e => console.log('onMouseLeave (first button)')} onMouseOver={e => console.log('onMouseOver (first button)')} onMouseUp={e => console.log('onMouseUp (first button)')} > First button </button> <button onClick={e => console.log('onClick (second button)')} onMouseDown={e => console.log('onMouseDown (second button)')} onMouseEnter={e => console.log('onMouseEnter (second button)')} onMouseLeave={e => console.log('onMouseLeave (second button)')} onMouseOver={e => console.log('onMouseOver (second button)')} onMouseUp={e => console.log('onMouseUp (second button)')} > Second button </button> </div> ); }
Handling pointer events 포인터 이벤트 처리하기
This example shows some common pointer events and when they fire. 이 예시는 몇 가지 일반적인 포인터 이벤트와 이벤트 발생 시점을 보여줍니다.
export default function PointerExample() { return ( <div onPointerEnter={e => console.log('onPointerEnter (parent)')} onPointerLeave={e => console.log('onPointerLeave (parent)')} style={{ padding: 20, backgroundColor: '#ddd' }} > <div onPointerDown={e => console.log('onPointerDown (first child)')} onPointerEnter={e => console.log('onPointerEnter (first child)')} onPointerLeave={e => console.log('onPointerLeave (first child)')} onPointerMove={e => console.log('onPointerMove (first child)')} onPointerUp={e => console.log('onPointerUp (first child)')} style={{ padding: 20, backgroundColor: 'lightyellow' }} > First child </div> <div onPointerDown={e => console.log('onPointerDown (second child)')} onPointerEnter={e => console.log('onPointerEnter (second child)')} onPointerLeave={e => console.log('onPointerLeave (second child)')} onPointerMove={e => console.log('onPointerMove (second child)')} onPointerUp={e => console.log('onPointerUp (second child)')} style={{ padding: 20, backgroundColor: 'lightblue' }} > Second child </div> </div> ); }
Handling focus events 포커스 이벤트 처리하기
In React, focus events bubble. You can use the currentTarget and relatedTarget to differentiate if the focusing or blurring events originated from outside of the parent element. The example shows how to detect focusing a child, focusing the parent element, and how to detect focus entering or leaving the whole subtree.
React에는 포커스 이벤트 버블이 있습니다. currentTarget 와 relatedTarget을 사용하여 포커스나 블러 이벤트가 부모 엘리먼트 외부에서 발생했는지 구분할 수 있습니다. 이 예는 자식 요소 포커싱, 부모 요소 포커싱, 전체 하위 트리에 들어오고 나가는 포커스를 감지하는 방법을 보여줍니다.
export default function FocusExample() { return ( <div tabIndex={1} onFocus={(e) => { if (e.currentTarget === e.target) { console.log('focused parent'); } else { console.log('focused child', e.target.name); } if (!e.currentTarget.contains(e.relatedTarget)) { // Not triggered when swapping focus between children // 자식 간에 포커스를 바꿀 때는 트리거되지 않습니다. console.log('focus entered parent'); } }} onBlur={(e) => { if (e.currentTarget === e.target) { console.log('unfocused parent'); } else { console.log('unfocused child', e.target.name); } if (!e.currentTarget.contains(e.relatedTarget)) { // Not triggered when swapping focus between children // 자식 간에 포커스를 바꿀 때는 트리거되지 않습니다. console.log('focus left parent'); } }} > <label> First name: <input name="firstName" /> </label> <label> Last name: <input name="lastName" /> </label> </div> ); }
Handling keyboard events 키보드 이벤트 처리하기
This example shows some common keyboard events and when they fire. 이 예는 몇 가지 일반적인 키보드 이벤트와 이벤트 발생 시점을 보여줍니다.
export default function KeyboardExample() { return ( <label> First name: <input name="firstName" onKeyDown={e => console.log('onKeyDown:', e.key, e.code)} onKeyUp={e => console.log('onKeyUp:', e.key, e.code)} /> </label> ); }