react学习---day03--限制props的数据
props让传值变得优雅,但是如果有时我并没有传入该值,我希望有一个默认值(类似于vue的filter)
首先有两个组件的渲染源
<div id="app1"></div> <div id="app2"></div>
然后是render函数
1 class App extends React.Component { 2 render() { 3 const { name, age, sex } = this.props 4 return ( 5 <ul> 6 <li>{name}</li> 7 <li>{age}</li> 8 <li>{sex}</li> 9 </ul> 10 ) 11 } 12 } 13 // 对props进行类型以及必填属性的限制 14 App.propTypes = { 15 name: PropTypes.string.isRequired, 16 age: PropTypes.number, 17 sex: PropTypes.string, 18 } 19 // 对props指定默认值 20 App.defaultProps = { 21 sex: "女", 22 age: 16, 23 } 24 const person = { 25 name: "张三", 26 age: 18, 27 sex: "男", 28 } 29 ReactDOM.render(<App {...person} />, document.getElementById("app1")) 30 ReactDOM.render(<App name="李四" />, document.getElementById("app2"))
其中需要注意的是在React16版本之后React本身已经不支持直接React.PropTypes了,需要再导入一个prop-types的js包
<script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script>
具体的props限制有很多方法可以参考react官方文档 https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html
其中还有一种方法是将限制对象放入class类里面
1 class App extends React.Component { 2 // 对props进行类型以及必填属性的限制,当限制类型为函数的时候记得函数是func为了避免与其他关键字起冲突 3 static propTypes = { 4 name: PropTypes.string.isRequired, 5 age: PropTypes.number, 6 sex: PropTypes.string, 7 } 8 // 对props指定默认值 9 static defaultProps = { 10 sex: "女", 11 age: 16, 12 } 13 render() { 14 const { name, age, sex } = this.props 15 return ( 16 <ul> 17 <li>{name}</li> 18 <li>{age}</li> 19 <li>{sex}</li> 20 </ul> 21 ) 22 } 23 }
static将propTypes绑定到了类上面,属于类的静态方法,只有类可以调用,而不是类的实例的方法,与typescript中的static有异曲同工之妙

浙公网安备 33010602011771号