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
网友评论