React学习之高级DOM元素属性(二十六)

React实现了一个独立于浏览器的DOM系统,跨浏览器兼容性特别好。

React中, 所有的DOM属性包括事件绑定都要使用托蜂命名法,比如tabindexReact中就变成了tabIndex,同时需要显示在DOM的属性需要用这两个前缀而且必须是小写,aria-*data-*

1.一些特殊的DOM属性在React中的处理

checked

这个属性用在checkboxradio中,可以使用它检测组件是不是被选择,defaultChecked设置可以让组件默认被选择

className

除了是WEB组件外都应该使用className,WEB组件则直接使用class

dangerouslySetInnerHTML

这个是React用来代替浏览器中DOM操作innerHTML的,一般来说,直接设置HTML代码是有风险的,可能会造成XSS攻击,在前面我们说JSX中插入表达式时也说过,{}默认会对内部的变量进行编码,防止发生XSS攻击。

但是,你可以通过React直接输出HTML,但是你需要做一些处理,分为如下两个步骤。

  1. 先创建一个对象,这个对象有一个__htmlkey键来处理需要输出的HTML数据

  2. 然后通过dangerouslySetInnerHTML对这个数据进行输出就可以了。

function createMarkup() {
  return {__html: 'First · Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

虽然是这样的,但是有一点需要记住的就是,这样做是危险的,XSS攻击无处不在啊。

htmlFor

由于forjavascript的保留字,所以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', // webkit浏览器
  msTransition: 'all' // ms IE浏览器,注意是小写
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browser</div>;
}

suppressContentEditableWarning

看到这个属性名字大家或许就已经够明白了,这是针对contentEditable处理的,在React中,如果一个元素有子节点,而它自己又标记了contentEditable的话就会报警告,因为它并不会工作。(然而这个属性个人测试并没有什么卵用)

value

这个属性放在inputtextarea组件,可以使用它为组件设置值,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//用于Safari
<link rel="mask-icon" />中的color属性//在Safari
itemProp itemScope itemType itemRef itemID//HTML的微数据
security//古老的IE
unselectable//IE
results autoSave//webkit/blink对于search额外的支持

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中的事件系统

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值