一、属性验证
1 安装
npm i prop-types
2 使用
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class Fifth extends Component {
//static 定义类属性,可以在类外Fifth.proTypes直接使用
static propTypes = {
title: PropTypes.string,//规定title为字符串
isAdmin: PropTypes.bool//规定isAdmin为布尔值
}
//对象属性,若想要在类外使用,需要这样写:new Fifth().a
a=100
render() {
return (
<div>
{this.props.title}
{this.props.isAdmin && <button>点击</button>}
</div>
)
}
}
错误传值:
ReactDOM.render(<Fifth title="rain" isAdmin="true" />, document.getElementById("root"))
报错:
Warning: Failed prop type: Invalid prop isAdmin
of type string
supplied to Fifth
, expected boolean
.
正确传值:
ReactDOM.render(<Fifth title="rain" isAdmin={true} />, document.getElementById("root"))