React 实现了一个独立于浏览器的DOM 系统,跨浏览器兼容性特别好。
在React 中, 所有的DOM 属性包括事件绑定都要使用托蜂命名法,比如tabindex 在React 中就变成了tabIndex ,同时需要显示在DOM 的属性需要用这两个前缀而且必须是小写,aria-* 和data-*
1.一些特殊的DOM 属性在React 中的处理
checked
这个属性用在checkbox 和radio 中,可以使用它检测组件是不是被选择,defaultChecked设置可以让组件默认被选择
className
除了是WEB 组件外都应该使用className ,WEB 组件则直接使用class
dangerouslySetInnerHTML
这个是React 用来代替浏览器中DOM 操作innerHTML 的,一般来说,直接设置HTML 代码是有风险的,可能会造成XSS 攻击,在前面我们说JSX 中插入表达式时也说过,{} 默认会对内部的变量进行编码,防止发生XSS 攻击。
但是,你可以通过React 直接输出HTML ,但是你需要做一些处理,分为如下两个步骤。
先创建一个对象,这个对象有一个__html 的key 键来处理需要输出的HTML 数据
然后通过dangerouslySetInnerHTML 对这个数据进行输出就可以了。
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
虽然是这样的,但是有一点需要记住的就是,这样做是危险的,XSS 攻击无处不在啊。
htmlFor
由于for 是javascript 的保留字,所以React 使用htmlFor 来代替它,你可能有点困惑这个东西哪里用,在表单的label 中的for 属性用来绑定表单元素。
onChange
被React 独立出来,总的来说React 用它来实时响应用户的输入
selected
这个属性被使用在option 组件上
style
这个属性在React 中接受一个javascript 对象,同时属性的名称要是用驼峰命名法
const divStyle = {
color: 'blue',backgroundImage: 'url(' + imgUrl + ')',};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
兼容性问题处理
const divStyle = {
WebkitTransition: 'all',
msTransition: 'all'
};
function ComponentWithTransition() {
return <div style={divStyle}>This should work cross-browser</div>;
}
suppressContentEditableWarning
看到这个属性名字大家或许就已经够明白了,这是针对contentEditable 处理的,在React 中,如果一个元素有子节点,而它自己又标记了contentEditable 的话就会报警告,因为它并不会工作。(然而这个属性个人测试并没有什么卵用)
value
这个属性放在input 和textarea 组件,可以使用它为组件设置值,defaultValue 用于设置默认值
2.在React 中更没有被特殊化的属性
这些没有特殊化的属性都必须要通过data-* 和aria-* 来加入JSXDOM 语句中
accept acceptCharset accessKey action allowFullScreen allowTransparency alt async autoComplete autoFocus autoPlay
capture cellPadding cellSpacing challenge charSet checked cite classID className colSpan cols content contentEditable contextMenu controls coords crossOrigin
data dateTime default defer dir disabled download draggable
encType
form formAction formEncType formMethod formNoValidate formTarget
frameBorder
headers height hidden high href hrefLang htmlFor httpEquiv
icon id inputMode integrity is
keyParams keyType kind
label lang list loop low
manifest marginHeight marginWidth max maxLength media mediaGroup method min minLength multiple muted name noValidate nonce open optimum pattern placeholder poster preload profile radioGroup readOnly rel required reversed role rowSpan rows sandbox scope scoped scrolling seamless selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step style summary tabIndex target title type useMap value width wmode wrap
其中针对RDFa 标准的处理,如下
about datatype inlist prefix property resource typeof vocab
除此之外还有几个非标准的属性
autoCapitalize autoCorrect
<link rel="mask-icon" />中的color属性
itemProp itemScope itemType itemRef itemID
security
unselectable
results autoSave
3.React 支持并且没有特殊化的SVG 属性
accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
clip clipPath clipPathUnits clipRule colorInterpolation
colorInterpolationFilters colorProfile colorRendering contentScriptType
contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
end exponent externalResourcesRequired fill fillOpacity fillRule filter
filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
limitingConeAngle local markerEnd markerHeight markerMid markerStart
markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
numOctaves offset opacity operator order orient orientation origin overflow
overlinePosition overlineThickness paintOrder panose1 pathLength
patternContentUnits patternTransform patternUnits pointerEvents points
pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
spacing specularConstant specularExponent speed spreadMethod startOffset
stdDeviation stemh stemv stitchTiles stopColor stopOpacity
strikethroughPosition strikethroughThickness string stroke strokeDasharray
strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
textDecoration textLength textRendering to transform u1 u2 underlinePosition
underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlns xmlnsXlink xmlBase
xmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan
下一篇将讲React 中的事件系统
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|