React prop-types 数据有效性验证

2018-06-22  本文已影响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

上一篇 下一篇

猜你喜欢

热点阅读