设置默许 defaultProps
class ExampleComponent extends React.Component{
static defaultProps = {
value: 0
}
...
}
/*-------------------------------*/
class ExampleComponent extends React.Component{
...
}
ExampleComponent.defaultProps = {
value: 0
}
ref和React中的DOM操纵
React.js并不能完整满足一切DOM操纵需求,有些时刻照样须要和DOM打交道。比方进入页面后自动focus到某个输入框,这是须要挪用input.focus()
的DOM API。React当中供应了ref
属性来协助我们猎取 已挂载元素 的DOM节点。详细的运用方法以下:
class ExampleInput extends Component {
componentDidMount () {
this.input.focus()
}
render () {
return (
<input ref={(input) => this.input = input} />
)
}
}
能够看到我们给 input 元素加了一个 ref 属性,这个属性值是一个函数。当 input 元素在页面上挂载完成今后 ,React 就会挪用这个函数,而且把这个挂载今后的 DOM 节点传给这个函数。在函数中我们把这个 DOM 元素设置为组件实例的一个属性,如许今后我们就能够经由过程 this.input 猎取到这个 DOM 元素。
dangerouslySetInnerHTML
出于平安斟酌的缘由(XSS 进击),在 React当中一切经由过程表达式插进去的内容都会被自动转义
class ExampleComponent extends React.Component {
render () {
const content = '<h1>Hello World</h1>'
return (
<div className='editor-wrapper'>
{content}
</div>
)
}
}
在上面的例子中,content的内容会被自动转义,当组件被衬着后,页面显现的是文本情势的'<h1>Hello World</h1>’
假如想要动态的向元素内部插进去新的元素内容,该如何做呢?这时候就须要运用dangerouslySetInnerHTML属性了
class ExampleComponent extends React.Component {
render () {
const content = '<h1>Hello World</h1>'
return (
<div
className='example-component '
dangerouslySetInnerHTML={{__html: content}} />
)
}
}
组件参数考证
React供应了一种机制,能够给props中的属性举行范例考证.假如须要对参数举行范例考证,须要装置一个由React供应的第三方库prop-types
装置prop-types
npm install --save prop-types
运用prop-types考证参数范例
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class Comment extends Component {
static propTypes = {
comment: PropTypes.object // 请求 this.props.comment 必需是 object范例
}
....
prop-types供应的数据范例
PropTypes.array
PropTypes.bool
PropTypes.func
PropTypes.number
PropTypes.object
PropTypes.string
PropTypes.node
PropTypes.element
...