配置默认 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
- ...