React中的小知识点

前端之家收集整理的这篇文章主要介绍了React中的小知识点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

配置默认 defaultProps

  1. class ExampleComponent extends React.Component{
  2. static defaultProps = {
  3. value: 0
  4. }
  5. ...
  6. }
  7.  
  8. /*-------------------------------*/
  9. class ExampleComponent extends React.Component{
  10. ...
  11. }
  12. ExampleComponent.defaultProps = {
  13. value: 0
  14. }

ref和React中的DOM操作

React.js并不能完全满足所有DOM操作需求,有些时候还是需要和DOM打交道。比如进入页面自动focus到某个输入框,这是需要调用input.focus()的DOM API。React当中提供了ref属性来帮助我们获取 已经挂载元素 的DOM节点。具体的使用方法如下:

  1. class ExampleInput extends Component {
  2. componentDidMount () {
  3. this.input.focus()
  4. }
  5.  
  6. render () {
  7. return (
  8. <input ref={(input) => this.input = input} />
  9. )
  10. }
  11. }

可以看到我们给 input 元素加了一个 ref 属性,这个属性值是一个函数。当 input 元素在页面上挂载完成以后 ,React 就会调用这个函数,并且把这个挂载以后的 DOM 节点传给这个函数。在函数中我们把这个 DOM 元素设置为组件实例的一个属性,这样以后我们就可以通过 this.input 获取到这个 DOM 元素。

dangerouslySetInnerHTML

出于安全考虑的原因(XSS 攻击),在 React当中所有通过表达式插入的内容都会被自动转义

  1. class ExampleComponent extends React.Component {
  2. render () {
  3. const content = '<h1>Hello World</h1>'
  4. return (
  5. <div className='editor-wrapper'>
  6. {content}
  7. </div>
  8. )
  9. }
  10. }

在上面的例子中,content的内容会被自动转义,当组件被渲染后,页面显示的是文本形式的'<h1>Hello World</h1>'

如果想要动态的向元素内部插入新的元素内容,该如何做呢?这时就需要使用dangerouslySetInnerHTML属性

  1. class ExampleComponent extends React.Component {
  2. render () {
  3. const content = '<h1>Hello World</h1>'
  4. return (
  5. <div
  6. className='example-component '
  7. dangerouslySetInnerHTML={{__html: content}} />
  8. )
  9. }
  10. }

组件参数验证

React提供了一种机制,可以给props中的属性进行类型验证.如果需要对参数进行类型验证,需要安装一个由React提供的第三方库prop-types

安装prop-types

npm install --save prop-types

使用prop-types验证参数类型

  1. import React,{ Component } from 'react'
  2. import PropTypes from 'prop-types'
  3.  
  4. class Comment extends Component {
  5. static propTypes = {
  6. comment: PropTypes.object // 要求 this.props.comment 必须是 object类型
  7. }
  8. ....

prop-types提供的数据类型

  1. PropTypes.array
  2. PropTypes.bool
  3. PropTypes.func
  4. PropTypes.number
  5. PropTypes.object
  6. PropTypes.string
  7. PropTypes.node
  8. PropTypes.element
  9. ...

猜你在找的React相关文章