React(十一):props的类型限制
1.类外写法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>props类型限制</title> <script src="https://unpkg.com/react@18/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <!-- Don't use this in production: --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <!-- prop类型限制导入 --> <script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script> </head> <body> <div id="test1"></div> <div id="test2"></div> <div id="test3"></div> </body> <script type="text/babel"> class Person extends React.Component { render() { const { name, sex, age } = this.props return ( <ul> <li>姓名:{name}</li> <li>性别:{sex}</li> <li>年龄:{age}</li> </ul> ) } } //props类型限制 Person.propTypes = { name: PropTypes.string.isRequired,//是字符串类型且不能为空 sex: PropTypes.string,//是字符串类型 age: PropTypes.number,//是数值类型 speak: PropTypes.func//是函数类型 } //props默认值 Person.defaultProps = { age: 0, sex: '未知' } //基本使用 ReactDOM.render(<Person name="张三" age={15} sex="男" />, document.getElementById('test1')) ReactDOM.render(<Person name="李四" />, document.getElementById('test2')) //批量传递props const p = {name: "王五", age: 17, sex: "女", speak: function a(){}} ReactDOM.render(<Person {...p} />, document.getElementById('test3')) </script> </html>
2.类内写法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>props的简写形式</title> <script src="https://unpkg.com/react@18/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <!-- Don't use this in production: --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <!-- prop类型限制导入 --> <script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script> </head> <body> <div id="test1"></div> <div id="test2"></div> <div id="test3"></div> </body> <script type="text/babel"> class Person extends React.Component { //使用static之后,属性就不是在实例对象而是在原型对象上 //props类型限制 static propTypes = { name: PropTypes.string.isRequired,//是字符串类型且不能为空 sex: PropTypes.string,//是字符串类型 age: PropTypes.number,//是数值类型 speak: PropTypes.func//是函数类型 } //props默认值 static defaultProps = { age: 0, sex: '未知' } render() { const { name, sex, age } = this.props return ( <ul> <li>姓名:{name}</li> <li>性别:{sex}</li> <li>年龄:{age}</li> </ul> ) } } //基本使用 ReactDOM.render(<Person name="张三" age={15} sex="男" />, document.getElementById('test1')) ReactDOM.render(<Person name="李四" />, document.getElementById('test2')) //批量传递props const p = { name: "王五", age: 17, sex: "女", speak: function a() { } } ReactDOM.render(<Person {...p} />, document.getElementById('test3')) </script> </html>