Common components (e.g. <div>)
Kaikki selaimeen sisäänrakennetut komponentit, kuten <div>
, tukevat joitakin yleisiä propseja ja tapahtumia.
- Viite
- Yleiset komponentit (kuten
<div>
) ref
callback-funktio- React tapahtumaolio
AnimationEvent
käsittelijäfunktioClipboardEvent
käsittelijäfunktioCompositionEvent
käsittelijäfunktioDragEvent
käsittelijäfunktioFocusEvent
käsittelijäfunktioEvent
käsittelijäfunktioInputEvent
käsittelijäfunktioKeyboardEvent
käsittelijäfunktioMouseEvent
käsittelijäfunktioPointerEvent
käsittelijäfunktioTouchEvent
käsittelijäfunktioTransitionEvent
käsittelijäfunktioUIEvent
käsittelijäfunktioWheelEvent
käsittelijäfunktio
- Yleiset komponentit (kuten
- Käyttö
Viite
Yleiset komponentit (kuten <div>
)
<div className="wrapper">Jotain sisältöä</div>
Propsit
These special React props are supported for all built-in components:
-
children
: A React node (an element, a string, a number, a portal, an empty node likenull
,undefined
and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify thechildren
prop implicitly by nesting tags like<div><span /></div>
. -
dangerouslySetInnerHTML
: An object of the form{ __html: '<p>some html</p>' }
with a raw HTML string inside. Overrides theinnerHTML
property 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
. -
ref
: A ref object fromuseRef
orcreateRef
, or aref
callback 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. -
suppressContentEditableWarning
: Totuusarvo. Iftrue
, suppresses the warning that React shows for elements that both havechildren
andcontentEditable={true}
(which normally do not work together). Use this if you’re building a text input library that manages thecontentEditable
content manually. -
suppressHydrationWarning
: Totuusarvo. 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 setsuppressHydrationWarning
totrue
, 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. -
style
: An object with CSS styles, for example{ fontWeight: 'bold', margin: 20 }
. Similarly to the DOMstyle
property, the CSS property names need to be written ascamelCase
, for examplefontWeight
instead 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 usingstyle
only for dynamic styles where you don’t know the style values ahead of time. In other cases, applying plain CSS classes withclassName
is more efficient. Read more aboutclassName
andstyle
.
These standard DOM props are also supported for all built-in components:
accessKey
: Merkkijono. Specifies a keyboard shortcut for the element. Not generally recommended.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.autoCapitalize
: Merkkijono. Specifies whether and how the user input should be capitalized.className
: Merkkijono. Specifies the element’s CSS class name. Read more about applying CSS styles.contentEditable
: Totuusarvo. 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.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.dir
: Either'ltr'
or'rtl'
. Specifies the text direction of the element.draggable
: Totuusarvo. Specifies whether the element is draggable. Part of HTML Drag and Drop API.enterKeyHint
: Merkkijono. Specifies which action to present for the enter key on virtual keyboards.htmlFor
: Merkkijono. For<label>
and<output>
, lets you associate the label with some control. Same asfor
HTML attribute. React uses the standard DOM property names (htmlFor
) instead of HTML attribute names.hidden
: A boolean or a string. Specifies whether the element should be hidden.id
: Merkkijono. Specifies a unique identifier for this element, which can be used to find it later or connect it with other elements. Generate it withuseId
to avoid clashes between multiple instances of the same component.is
: Merkkijono. If specified, the component will behave like a custom element.inputMode
: Merkkijono. Specifies what kind of keyboard to display (for example, text, number or telephone).itemProp
: Merkkijono. Specifies which property the element represents for structured data crawlers.lang
: Merkkijono. Specifies the language of the element.onAnimationEnd
:AnimationEvent
käsittelijäfunktio. Fires when a CSS animation completes.onAnimationEndCapture
: VersioonAnimationEnd
:sta joka suoritetaan nappausvaiheessa.onAnimationIteration
:AnimationEvent
käsittelijäfunktio. Fires when an iteration of a CSS animation ends, and another one begins.onAnimationIterationCapture
: VersioonAnimationIteration
:sta joka suoritetaan nappausvaiheessa.onAnimationStart
:AnimationEvent
käsittelijäfunktio. Fires when a CSS animation starts.onAnimationStartCapture
:onAnimationStart
, but fires in the capture phase.onAuxClick
:MouseEvent
käsittelijäfunktio. Fires when a non-primary pointer button was clicked.onAuxClickCapture
: VersioonAuxClick
:sta joka suoritetaan nappausvaiheessa.onBeforeInput
:InputEvent
käsittelijäfunktio. Fires before the value of an editable element is modified. React does not yet use the nativebeforeinput
event, and instead attempts to polyfill it using other events.onBeforeInputCapture
: VersioonBeforeInput
:sta joka suoritetaan nappausvaiheessa.onBlur
:FocusEvent
käsittelijäfunktio. Fires when an element lost focus. Unlike the built-in browserblur
event, in React theonBlur
event bubbles.onBlurCapture
: VersioonBlur
:sta joka suoritetaan nappausvaiheessa.onClick
:MouseEvent
käsittelijäfunktio. Fires when the primary button was clicked on the pointing device.onClickCapture
: VersioonClick
:sta joka suoritetaan nappausvaiheessa.onCompositionStart
:CompositionEvent
käsittelijäfunktio. Fires when an input method editor starts a new composition session.onCompositionStartCapture
: VersioonCompositionStart
:sta joka suoritetaan nappausvaiheessa.onCompositionEnd
:CompositionEvent
käsittelijäfunktio. Fires when an input method editor completes or cancels a composition session.onCompositionEndCapture
: VersioonCompositionEnd
:sta joka suoritetaan nappausvaiheessa.onCompositionUpdate
:CompositionEvent
käsittelijäfunktio. Fires when an input method editor receives a new character.onCompositionUpdateCapture
: VersioonCompositionUpdate
:sta joka suoritetaan nappausvaiheessa.onContextMenu
:MouseEvent
käsittelijäfunktio. Fires when the user tries to open a context menu.onContextMenuCapture
: VersioonContextMenu
:sta joka suoritetaan nappausvaiheessa.onCopy
:ClipboardEvent
käsittelijäfunktio. Fires when the user tries to copy something into the clipboard.onCopyCapture
: VersioonCopy
:sta joka suoritetaan nappausvaiheessa.onCut
:ClipboardEvent
käsittelijäfunktio. Fires when the user tries to cut something into the clipboard.onCutCapture
: VersioonCut
:sta joka suoritetaan nappausvaiheessa.onDoubleClick
:MouseEvent
käsittelijäfunktio. Fires when the user clicks twice. Corresponds to the browserdblclick
event.onDoubleClickCapture
: VersioonDoubleClick
:sta joka suoritetaan nappausvaiheessa.onDrag
:DragEvent
käsittelijäfunktio. Fires while the user is dragging something.onDragCapture
: VersioonDrag
:sta joka suoritetaan nappausvaiheessa.onDragEnd
:DragEvent
käsittelijäfunktio. Fires when the user stops dragging something.onDragEndCapture
: VersioonDragEnd
:sta joka suoritetaan nappausvaiheessa.onDragEnter
:DragEvent
käsittelijäfunktio. Fires when the dragged content enters a valid drop target.onDragEnterCapture
: VersioonDragEnter
:sta joka suoritetaan nappausvaiheessa.onDragOver
:DragEvent
käsittelijäfunktio. Fires on a valid drop target while the dragged content is dragged over it. You must calle.preventDefault()
here to allow dropping.onDragOverCapture
: VersioonDragOver
:sta joka suoritetaan nappausvaiheessa.onDragStart
:DragEvent
käsittelijäfunktio. Fires when the user starts dragging an element.onDragStartCapture
: VersioonDragStart
:sta joka suoritetaan nappausvaiheessa.onDrop
:DragEvent
käsittelijäfunktio. Fires when something is dropped on a valid drop target.onDropCapture
: VersioonDrop
:sta joka suoritetaan nappausvaiheessa.onFocus
:FocusEvent
käsittelijäfunktio. Fires when an element receives focus. Unlike the built-in browserfocus
event, in React theonFocus
event bubbles.onFocusCapture
: VersioonFocus
:sta joka suoritetaan nappausvaiheessa.onGotPointerCapture
:PointerEvent
käsittelijäfunktio. Fires when an element programmatically captures a pointer.onGotPointerCaptureCapture
: VersioonGotPointerCapture
:sta joka suoritetaan nappausvaiheessa.onKeyDown
:KeyboardEvent
käsittelijäfunktio. Fires when a key is pressed.onKeyDownCapture
: VersioonKeyDown
:sta joka suoritetaan nappausvaiheessa.onKeyPress
:KeyboardEvent
käsittelijäfunktio. Deprecated. UseonKeyDown
oronBeforeInput
instead.onKeyPressCapture
: VersioonKeyPress
:sta joka suoritetaan nappausvaiheessa.onKeyUp
:KeyboardEvent
käsittelijäfunktio. Fires when a key is released.onKeyUpCapture
: VersioonKeyUp
:sta joka suoritetaan nappausvaiheessa.onLostPointerCapture
:PointerEvent
käsittelijäfunktio. Fires when an element stops capturing a pointer.onLostPointerCaptureCapture
: VersioonLostPointerCapture
:sta joka suoritetaan nappausvaiheessa.onMouseDown
:MouseEvent
käsittelijäfunktio. Fires when the pointer is pressed down.onMouseDownCapture
: VersioonMouseDown
:sta joka suoritetaan nappausvaiheessa.onMouseEnter
:MouseEvent
käsittelijäfunktio. Fires when the pointer moves inside an element. Does not have a capture phase. Instead,onMouseLeave
andonMouseEnter
propagate from the element being left to the one being entered.onMouseLeave
:MouseEvent
käsittelijäfunktio. Fires when the pointer moves outside an element. Does not have a capture phase. Instead,onMouseLeave
andonMouseEnter
propagate from the element being left to the one being entered.onMouseMove
:MouseEvent
käsittelijäfunktio. Fires when the pointer changes coordinates.onMouseMoveCapture
: VersioonMouseMove
:sta joka suoritetaan nappausvaiheessa.onMouseOut
:MouseEvent
käsittelijäfunktio. Fires when the pointer moves outside an element, or if it moves into a child element.onMouseOutCapture
: VersioonMouseOut
:sta joka suoritetaan nappausvaiheessa.onMouseUp
:MouseEvent
käsittelijäfunktio. Fires when the pointer is released.onMouseUpCapture
: VersioonMouseUp
:sta joka suoritetaan nappausvaiheessa.onPointerCancel
:PointerEvent
käsittelijäfunktio. Fires when the browser cancels a pointer interaction.onPointerCancelCapture
: VersioonPointerCancel
:sta joka suoritetaan nappausvaiheessa.onPointerDown
:PointerEvent
käsittelijäfunktio. Fires when a pointer becomes active.onPointerDownCapture
: VersioonPointerDown
:sta joka suoritetaan nappausvaiheessa.onPointerEnter
:PointerEvent
käsittelijäfunktio. Fires when a pointer moves inside an element. Does not have a capture phase. Instead,onPointerLeave
andonPointerEnter
propagate from the element being left to the one being entered.onPointerLeave
:PointerEvent
käsittelijäfunktio. Fires when a pointer moves outside an element. Does not have a capture phase. Instead,onPointerLeave
andonPointerEnter
propagate from the element being left to the one being entered.onPointerMove
:PointerEvent
käsittelijäfunktio. Fires when a pointer changes coordinates.onPointerMoveCapture
: VersioonPointerMove
:sta joka suoritetaan nappausvaiheessa.onPointerOut
:PointerEvent
käsittelijäfunktio. Fires when a pointer moves outside an element, if the pointer interaction is cancelled, and a few other reasons.onPointerOutCapture
: VersioonPointerOut
:sta joka suoritetaan nappausvaiheessa.onPointerUp
:PointerEvent
käsittelijäfunktio. Fires when a pointer is no longer active.onPointerUpCapture
: VersioonPointerUp
:sta joka suoritetaan nappausvaiheessa.onPaste
:ClipboardEvent
käsittelijäfunktio. Fires when the user tries to paste something from the clipboard.onPasteCapture
: VersioonPaste
:sta joka suoritetaan nappausvaiheessa.onScroll
:Event
käsittelijäfunktio. Fires when an element has been scrolled. This event does not bubble.onScrollCapture
: VersioonScroll
:sta joka suoritetaan nappausvaiheessa.onSelect
:Event
käsittelijäfunktio. Fires after the selection inside an editable element like an input changes. React extends theonSelect
event 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).onSelectCapture
: VersioonSelect
:sta joka suoritetaan nappausvaiheessa.onTouchCancel
:TouchEvent
käsittelijäfunktio. Fires when the browser cancels a touch interaction.onTouchCancelCapture
: VersioonTouchCancel
:sta joka suoritetaan nappausvaiheessa.onTouchEnd
:TouchEvent
käsittelijäfunktio. Fires when one or more touch points are removed.onTouchEndCapture
: VersioonTouchEnd
:sta joka suoritetaan nappausvaiheessa.onTouchMove
:TouchEvent
käsittelijäfunktio. Fires one or more touch points are moved.onTouchMoveCapture
: VersioonTouchMove
:sta joka suoritetaan nappausvaiheessa.onTouchStart
:TouchEvent
käsittelijäfunktio. Fires when one or more touch points are placed.onTouchStartCapture
: VersioonTouchStart
:sta joka suoritetaan nappausvaiheessa.onTransitionEnd
:TransitionEvent
käsittelijäfunktio. Fires when a CSS transition completes.onTransitionEndCapture
: VersioonTransitionEnd
:sta joka suoritetaan nappausvaiheessa.onWheel
:WheelEvent
käsittelijäfunktio. Fires when the user rotates a wheel button.onWheelCapture
: VersioonWheel
:sta joka suoritetaan nappausvaiheessa.role
: Merkkijono. Specifies the element role explicitly for assistive technologies.slot
: Merkkijono. 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 />} />
.spellCheck
: A boolean or null. If explicitly set totrue
orfalse
, enables or disables spellchecking.tabIndex
: Numero. Overrides the default Tab button behavior. Avoid using values other than-1
and0
.title
: Merkkijono. Specifies the tooltip text for the element.translate
: Either'yes'
or'no'
. Passing'no'
excludes the element content from being translated.
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.
These events fire only for the <form>
elements:
onReset
:Event
käsittelijäfunktio. Fires when a form gets reset.onResetCapture
: VersioonReset
:sta joka suoritetaan nappausvaiheessa.onSubmit
:Event
käsittelijäfunktio. Fires when a form gets submitted.onSubmitCapture
: VersioonSubmit
:sta joka suoritetaan nappausvaiheessa.
These events fire only for the <dialog>
elements. Unlike browser events, they bubble in React:
onCancel
:Event
käsittelijäfunktio. Fires when the user tries to dismiss the dialog.onCancelCapture
: VersioonCancel
:sta joka suoritetaan nappausvaiheessa.onClose
:Event
käsittelijäfunktio. Fires when a dialog has been closed.onCloseCapture
: VersioonClose
:sta joka suoritetaan nappausvaiheessa.
These events fire only for the <details>
elements. Unlike browser events, they bubble in React:
onToggle
:Event
käsittelijäfunktio. Fires when the user toggles the details.onToggleCapture
: VersioonToggle
:sta joka suoritetaan nappausvaiheessa.
These events fire for <img>
, <iframe>
, <object>
, <embed>
, <link>
, and SVG <image>
elements. Unlike browser events, they bubble in React:
onLoad
:Event
käsittelijäfunktio. Fires when the resource has loaded.onLoadCapture
: VersioonLoad
:sta joka suoritetaan nappausvaiheessa.onError
:Event
käsittelijäfunktio. Fires when the resource could not be loaded.onErrorCapture
: VersioonError
:sta joka suoritetaan nappausvaiheessa.
These events fire for resources like <audio>
and <video>
. Unlike browser events, they bubble in React:
onAbort
:Event
käsittelijäfunktio. Fires when the resource has not fully loaded, but not due to an error.onAbortCapture
: VersioonAbort
:sta joka suoritetaan nappausvaiheessa.onCanPlay
:Event
käsittelijäfunktio. Fires when there’s enough data to start playing, but not enough to play to the end without buffering.onCanPlayCapture
: VersioonCanPlay
:sta joka suoritetaan nappausvaiheessa.onCanPlayThrough
:Event
käsittelijäfunktio. Fires when there’s enough data that it’s likely possible to start playing without buffering until the end.onCanPlayThroughCapture
: VersioonCanPlayThrough
:sta joka suoritetaan nappausvaiheessa.onDurationChange
:Event
käsittelijäfunktio. Fires when the media duration has updated.onDurationChangeCapture
: VersioonDurationChange
:sta joka suoritetaan nappausvaiheessa.onEmptied
:Event
käsittelijäfunktio. Fires when the media has become empty.onEmptiedCapture
: VersioonEmptied
:sta joka suoritetaan nappausvaiheessa.onEncrypted
:Event
käsittelijäfunktio. Fires when the browser encounters encrypted media.onEncryptedCapture
: VersioonEncrypted
:sta joka suoritetaan nappausvaiheessa.onEnded
:Event
käsittelijäfunktio. Fires when the playback stops because there’s nothing left to play.onEndedCapture
: VersioonEnded
:sta joka suoritetaan nappausvaiheessa.onError
:Event
käsittelijäfunktio. Fires when the resource could not be loaded.onErrorCapture
: VersioonError
:sta joka suoritetaan nappausvaiheessa.onLoadedData
:Event
käsittelijäfunktio. Fires when the current playback frame has loaded.onLoadedDataCapture
: VersioonLoadedData
:sta joka suoritetaan nappausvaiheessa.onLoadedMetadata
:Event
käsittelijäfunktio. Fires when metadata has loaded.onLoadedMetadataCapture
: VersioonLoadedMetadata
:sta joka suoritetaan nappausvaiheessa.onLoadStart
:Event
käsittelijäfunktio. Fires when the browser started loading the resource.onLoadStartCapture
: VersioonLoadStart
:sta joka suoritetaan nappausvaiheessa.onPause
:Event
käsittelijäfunktio. Fires when the media was paused.onPauseCapture
: VersioonPause
:sta joka suoritetaan nappausvaiheessa.onPlay
:Event
käsittelijäfunktio. Fires when the media is no longer paused.onPlayCapture
: VersioonPlay
:sta joka suoritetaan nappausvaiheessa.onPlaying
:Event
käsittelijäfunktio. Fires when the media starts or restarts playing.onPlayingCapture
: VersioonPlaying
:sta joka suoritetaan nappausvaiheessa.onProgress
:Event
käsittelijäfunktio. Fires periodically while the resource is loading.onProgressCapture
: VersioonProgress
:sta joka suoritetaan nappausvaiheessa.onRateChange
:Event
käsittelijäfunktio. Fires when playback rate changes.onRateChangeCapture
: VersioonRateChange
:sta joka suoritetaan nappausvaiheessa.onResize
:Event
käsittelijäfunktio. Fires when video changes size.onResizeCapture
: VersioonResize
:sta joka suoritetaan nappausvaiheessa.onSeeked
:Event
käsittelijäfunktio. Fires when a seek operation completes.onSeekedCapture
: VersioonSeeked
:sta joka suoritetaan nappausvaiheessa.onSeeking
:Event
käsittelijäfunktio. Fires when a seek operation starts.onSeekingCapture
: VersioonSeeking
:sta joka suoritetaan nappausvaiheessa.onStalled
:Event
käsittelijäfunktio. Fires when the browser is waiting for data but it keeps not loading.onStalledCapture
: VersioonStalled
:sta joka suoritetaan nappausvaiheessa.onSuspend
:Event
käsittelijäfunktio. Fires when loading the resource was suspended.onSuspendCapture
: VersioonSuspend
:sta joka suoritetaan nappausvaiheessa.onTimeUpdate
:Event
käsittelijäfunktio. Fires when the current playback time updates.onTimeUpdateCapture
: VersioonTimeUpdate
:sta joka suoritetaan nappausvaiheessa.onVolumeChange
:Event
käsittelijäfunktio. Fires when the volume has changed.onVolumeChangeCapture
: VersioonVolumeChange
:sta joka suoritetaan nappausvaiheessa.onWaiting
:Event
käsittelijäfunktio. Fires when the playback stopped due to temporary lack of data.onWaitingCapture
: VersioonWaiting
:sta joka suoritetaan nappausvaiheessa.
Rajoitukset
- You cannot pass both
children
anddangerouslySetInnerHTML
at the same time. - Some events (like
onAbort
andonLoad
) don’t bubble in the browser, but bubble in React.
ref
callback-funktio
Instead of a ref object (like the one returned by useRef
), you may pass a function to the ref
attribute.
<div ref={(node) => console.log(node)} />
See an example of using the ref
callback.
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
.
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.
Parametrit
node
: A DOM node ornull
. React will pass you the DOM node when the ref gets attached, andnull
when the ref gets detached. Unless you pass the same function reference for theref
callback on every render, the callback will get temporarily detached and re-attached during every re-render of the component.
Palautukset
Do not return anything from the ref
callback.
React tapahtumaolio
Your event handlers will receive a React event object. It is also sometimes known as a “synthetic event”.
<button onClick={e => {
console.log(e); // React event object
}} />
It conforms to the same standard as the underlying DOM events, but fixes some browser inconsistencies.
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
.
Ominaisuudet
React event objects implement some of the standard Event
properties:
bubbles
: Totuusarvo. Returns whether the event bubbles through the DOM.cancelable
: Totuusarvo. Returns whether the event can be canceled.currentTarget
: A DOM node. Returns the node to which the current handler is attached in the React tree.defaultPrevented
: Totuusarvo. Returns whetherpreventDefault
was called.eventPhase
: Numero. Returns which phase the event is currently in.isTrusted
: Totuusarvo. Returns whether the event was initiated by user.target
: A DOM node. Returns the node on which the event has occurred (which could be a distant child).timeStamp
: Numero. Returns the time when the event occurred.
Additionally, React event objects provide these properties:
nativeEvent
: A DOMEvent
. The original browser event object.
Metodit
React event objects implement some of the standard Event
methods:
preventDefault()
: Prevents the default browser action for the event.stopPropagation()
: Stops the event propagation through the React tree.
Additionally, React event objects provide these methods:
isDefaultPrevented()
: Returns a boolean value indicating whetherpreventDefault
was called.isPropagationStopped()
: Returns a boolean value indicating whetherstopPropagation
was called.persist()
: Not used with React DOM. With React Native, call this to read event’s properties after the event.isPersistent()
: Not used with React DOM. With React Native, returns whetherpersist
has been called.
Rajoitukset
- The values of
currentTarget
,eventPhase
,target
, andtype
reflect 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.currentTarget
may not be the same as the underlyinge.nativeEvent.currentTarget
. For polyfilled events,e.type
(React event type) may differ frome.nativeEvent.type
(underlying type).
AnimationEvent
käsittelijäfunktio
An event handler type for the CSS animation events.
<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>
Parametrit
e
: A React event object with these extraAnimationEvent
properties:
ClipboardEvent
käsittelijäfunktio
An event handler type for the Clipboard API events.
<input
onCopy={e => console.log('onCopy')}
onCut={e => console.log('onCut')}
onPaste={e => console.log('onPaste')}
/>
Parametrit
-
e
: A React event object with these extraClipboardEvent
properties:
CompositionEvent
käsittelijäfunktio
An event handler type for the input method editor (IME) events.
<input
onCompositionStart={e => console.log('onCompositionStart')}
onCompositionUpdate={e => console.log('onCompositionUpdate')}
onCompositionEnd={e => console.log('onCompositionEnd')}
/>
Parametrit
e
: A React event object with these extraCompositionEvent
properties:
DragEvent
käsittelijäfunktio
An event handler type for the HTML Drag and Drop API events.
<>
<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>
</>
Parametrit
-
e
: A React event object with these extraDragEvent
properties:It also includes the inherited
MouseEvent
properties:altKey
button
buttons
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
It also includes the inherited
UIEvent
properties:
FocusEvent
käsittelijäfunktio
An event handler type for the focus events.
<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>
Parametrit
-
e
: A React event object with these extraFocusEvent
properties:It also includes the inherited
UIEvent
properties:
Event
käsittelijäfunktio
An event handler type for generic events.
Parametrit
e
: A React event object with no additional properties.
InputEvent
käsittelijäfunktio
An event handler type for the onBeforeInput
event.
<input onBeforeInput={e => console.log('onBeforeInput')} />
Parametrit
e
: A React event object with these extraInputEvent
properties:
KeyboardEvent
käsittelijäfunktio
An event handler type for keyboard events.
<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>
Parametrit
-
e
: A React event object with these extraKeyboardEvent
properties:altKey
charCode
code
ctrlKey
getModifierState(key)
key
keyCode
locale
metaKey
location
repeat
shiftKey
which
It also includes the inherited
UIEvent
properties:
MouseEvent
käsittelijäfunktio
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')}
/>
Parametrit
-
e
: A React event object with these extraMouseEvent
properties:altKey
button
buttons
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
It also includes the inherited
UIEvent
properties:
PointerEvent
käsittelijäfunktio
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')}
/>
Parametrit
-
e
: A React event object with these extraPointerEvent
properties:It also includes the inherited
MouseEvent
properties:altKey
button
buttons
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
It also includes the inherited
UIEvent
properties:
TouchEvent
käsittelijäfunktio
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')}
/>
Parametrit
-
e
: A React event object with these extraTouchEvent
properties:It also includes the inherited
UIEvent
properties:
TransitionEvent
käsittelijäfunktio
An event handler type for the CSS transition events.
<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>
Parametrit
e
: A React event object with these extraTransitionEvent
properties:
UIEvent
käsittelijäfunktio
An event handler type for generic UI events.
<div
onScroll={e => console.log('onScroll')}
/>
Parametrit
e
: A React event object with these extraUIEvent
properties:
WheelEvent
käsittelijäfunktio
An event handler type for the onWheel
event.
<div
onScroll={e => console.log('onScroll')}
/>
Parametrit
-
e
: A React event object with these extraWheelEvent
properties:It also includes the inherited
MouseEvent
properties:altKey
button
buttons
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
It also includes the inherited
UIEvent
properties:
Käyttö
CSS tyylien käyttö
In React, you specify a CSS class with className
. It works like the class
attribute in HTML:
<img className="avatar" />
Then you write the CSS rules for it in a separate CSS file:
/* 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.
Sometimes, the style values depend on data. Use the style
attribute to pass some styles dynamically:
<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.
export default function Avatar({ user }) { return ( <img src={user.imageUrl} alt={'Photo of ' + user.name} className="avatar" style={{ width: user.imageSize, height: user.imageSize }} /> ); }
Syväsukellus
To apply CSS classes conditionally, you need to produce the className
string yourself using JavaScript.
For example, className={'row ' + (isSelected ? 'selected': '')}
will produce either className="row"
or className="row selected"
depending on whether isSelected
is true
.
To make this more readable, you can use a tiny helper library like 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>
);
}
DOM elemetin manipuolinti refillä
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.
To obtain the browser DOM node for a tag, declare a ref and pass it as the ref
attribute to that tag:
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.
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.
For more advanced use cases, the ref
attribute also accepts a callback function.
Sisäisen HTML sisällön asettaminen vaarallisesti
You can pass a raw HTML string to an element like so:
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.
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:
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} />; }
To see why rendering arbitrary HTML is dangerous, replace the code above with this:
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
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.
Hiiren tapahtumien käsitteleminen
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> ); }
Osoittimen tapahtumien käsitteleminen
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> ); }
Kohdennustapahtumien käsitteleminen
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.
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> ); }
Näppäimistötapahtumien käsitteleminen
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> ); }