美文网首页
React prop-types 数据有效性验证

React prop-types 数据有效性验证

作者: 不知道的是 | 来源:发表于2018-06-22 14:38 被阅读0次

Runtime type checking for React props and similar objects.

./main.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

class App extends Component {

  static propTypes = {
    currentTime: PropTypes.string.isRequired // expected `string`
  }

  render() {
    return (
      <div>{ this.props.currentTime }</div>
    )
  }
}

ReactDOM.render(
  <App currentTime={new Date().toLocaleString()} />,
  document.getElementById('app')
)

数据不合法时

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

console.log((new Date()).constructor.name) // 'Date'

class App extends Component {

  static propTypes = {
    currentTime: PropTypes.string.isRequired
  }

  render() {
    return (
      <div>{ this.props.currentTime }</div>
    )
  }
}

ReactDOM.render(
  <App currentTime={new Date()} />,
  document.getElementById('app')
)
error message

参考资料:
https://www.npmjs.com/package/prop-types

相关文章

网友评论

      本文标题:React prop-types 数据有效性验证

      本文链接:https://www.haomeiwen.com/subject/uvykyftx.html