加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React中的小知识点

发布时间:2020-12-15 07:18:14 所属栏目:百科 来源:网络整理
导读:配置默认 defaultProps class ExampleComponent extends React.Component{ static defaultProps = { value: 0 } ...}/*-------------------------------*/class ExampleComponent extends React.Component{ ...}ExampleComponent.defaultProps = { value: 0}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读