Movatterモバイル変換


[0]ホーム

URL:


We want to hear from you!Take our 2021 Community Survey!
This site is no longer updated.Go to react.dev

DOM Elements

These docs are old and won’t be updated. Go toreact.dev for the new React docs.

These new documentation pages teach modern React and include live examples:

React implements a browser-independent DOM system for performance and cross-browser compatibility. We took the opportunity to clean up a few rough edges in browser DOM implementations.

In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attributetabindex corresponds to the attributetabIndex in React. The exception isaria-* anddata-* attributes, which should be lowercased. For example, you can keeparia-label asaria-label.

Differences In Attributes

There are a number of attributes that work differently between React and HTML:

checked

Thechecked attribute is supported by<input> components of typecheckbox orradio. You can use it to set whether the component is checked. This is useful for building controlled components.defaultChecked is the uncontrolled equivalent, which sets whether the component is checked when it is first mounted.

className

To specify a CSS class, use theclassName attribute. This applies to all regular DOM and SVG elements like<div>,<a>, and others.

If you use React with Web Components (which is uncommon), use theclass attribute instead.

dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for usinginnerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to across-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type outdangerouslySetInnerHTML and pass an object with a__html key, to remind yourself that it’s dangerous. For example:

functioncreateMarkup(){return{__html:'First &middot; Second'};}functionMyComponent(){return<divdangerouslySetInnerHTML={createMarkup()}/>;}

htmlFor

Sincefor is a reserved word in JavaScript, React elements usehtmlFor instead.

onChange

TheonChange event behaves as you would expect it to: whenever a form field is changed, this event is fired. We intentionally do not use the existing browser behavior becauseonChange is a misnomer for its behavior and React relies on this event to handle user input in real time.

selected

If you want to mark an<option> as selected, reference the value of that option in thevalue of its<select> instead.Check out“The select Tag” for detailed instructions.

style

Note

Some examples in the documentation usestyle for convenience, butusing thestyle attribute as the primary means of styling elements is generally not recommended. In most cases,className should be used to reference classes defined in an external CSS stylesheet.style is most often used in React applications to add dynamically-computed styles at render time. See alsoFAQ: Styling and CSS.

Thestyle attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOMstyle JavaScript property, is more efficient, and prevents XSS security holes. For example:

const divStyle={color:'blue',backgroundImage:'url('+ imgUrl+')',};functionHelloWorldComponent(){return<divstyle={divStyle}>Hello World!</div>;}

Note that styles are not autoprefixed. To support older browsers, you need to supply corresponding style properties:

const divStyle={WebkitTransition:'all',// note the capital 'W' heremsTransition:'all'// 'ms' is the only lowercase vendor prefix};functionComponentWithTransition(){return<divstyle={divStyle}>This should work cross-browser</div>;}

Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g.node.style.backgroundImage). Vendor prefixesother thanms should begin with a capital letter. This is whyWebkitTransition has an uppercase “W”.

React will automatically append a “px” suffix to certain numeric inline style properties. If you want to use units other than “px”, specify the value as a string with the desired unit. For example:

// Result style: '10px'<divstyle={{height:10}}>  Hello World!</div>// Result style: '10%'<divstyle={{height:'10%'}}>  Hello World!</div>

Not all style properties are converted to pixel strings though. Certain ones remain unitless (egzoom,order,flex). A complete list of unitless properties can be seenhere.

suppressContentEditableWarning

Normally, there is a warning when an element with children is also marked ascontentEditable, because it won’t work. This attribute suppresses that warning. Don’t use this unless you are building a library likeDraft.js that managescontentEditable manually.

suppressHydrationWarning

If you use server-side React rendering, normally there is a warning when the server and the client render different content. However, in some rare cases, it is very hard or impossible to guarantee an exact match. For example, timestamps are expected to differ on the server and on the client.

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. You can read more about hydration in theReactDOM.hydrateRoot() documentation.

value

Thevalue attribute is supported by<input>,<select> and<textarea> components. You can use it to set the value of the component. This is useful for building controlled components.defaultValue is the uncontrolled equivalent, which sets the value of the component when it is first mounted.

All Supported HTML Attributes

As of React 16, any standardor custom DOM attributes are fully supported.

React has always provided a JavaScript-centric API to the DOM. Since React components often take both custom and DOM-related props, React uses thecamelCase convention just like the DOM APIs:

<divtabIndex={-1}/>// Just like node.tabIndex DOM API<divclassName="Button"/>// Just like node.className DOM API<inputreadOnly={true}/>// Just like node.readOnly DOM API

These props work similarly to the corresponding HTML attributes, with the exception of the special cases documented above.

Some of the DOM attributes supported by React include:

accept acceptCharset accessKey action allowFullScreen alt async autoCompleteautoFocus autoPlay capture cellPadding cellSpacing challenge charSet checkedcite classID className colSpan cols content contentEditable contextMenu controlscontrolsList coords crossOrigin data dateTime default defer dir disableddownload draggable encType form formAction formEncType formMethod formNoValidateformTarget frameBorder headers height hidden high href hrefLang htmlForhttpEquiv icon id inputMode integrity is keyParams keyType kind label lang listloop low manifest marginHeight marginWidth max maxLength media mediaGroup methodmin minLength multiple muted name noValidate nonce open optimum patternplaceholder poster preload profile radioGroup readOnly rel required reversedrole rowSpan rows sandbox scope scoped scrolling seamless selected shape sizesizes span spellCheck src srcDoc srcLang srcSet start step style summarytabIndex target title type useMap value width wmode wrap

Similarly, all SVG attributes are fully supported:

accentHeight accumulate additive alignmentBaseline allowReorder alphabeticamplitude arabicForm ascent attributeName attributeType autoReverse azimuthbaseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeightclip clipPath clipPathUnits clipRule colorInterpolationcolorInterpolationFilters colorProfile colorRendering contentScriptTypecontentStyleType cursor cx cy d decelerate descent diffuseConstant directiondisplay divisor dominantBaseline dur dx dy edgeMode elevation enableBackgroundend exponent externalResourcesRequired fill fillOpacity fillRule filterfilterRes filterUnits floodColor floodOpacity focusable fontFamily fontSizefontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fyg1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRefgradientTransform gradientUnits hanging horizAdvX horizOriginX ideographicimageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLengthkerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColorlimitingConeAngle local markerEnd markerHeight markerMid markerStartmarkerUnits markerWidth mask maskContentUnits maskUnits mathematical modenumOctaves offset opacity operator order orient orientation origin overflowoverlinePosition overlineThickness paintOrder panose1 pathLengthpatternContentUnits patternTransform patternUnits pointerEvents pointspointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnitsr radius refX refY renderingIntent repeatCount repeatDur requiredExtensionsrequiredFeatures restart result rotate rx ry scale seed shapeRendering slopespacing specularConstant specularExponent speed spreadMethod startOffsetstdDeviation stemh stemv stitchTiles stopColor stopOpacitystrikethroughPosition strikethroughThickness string stroke strokeDasharraystrokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacitystrokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchortextDecoration textLength textRendering to transform u1 u2 underlinePositionunderlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabeticvHanging vIdeographic vMathematical values vectorEffect version vertAdvYvertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacingwritingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrolexlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlns xmlnsXlink xmlBasexmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan

You may also use custom attributes as long as they’re fully lowercase.

Is this page useful?Edit this page

[8]ページ先頭

©2009-2025 Movatter.jp