// 类式组件的 props 校验方法
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>
- Document
- </title>
- <script src="https:[email protected]/umd/react.development.js" crossorigin>
- </script>
- <!-- 该文件向外暴露了一个对象 React-Dom -->
- <script src="https:[email protected]/umd/react-dom.development.js" crossorigin>
- </script>
- <script src="https:[email protected]/babel.min.js">
- </script>
- <script src="https:[email protected]/babel.min.js">
- </script>
- <script src="https:[email protected]/prop-types.js">
- </script>
- </head>
- <body>
- <div id="app">
- </div>
- <script type="text/babel">
- class Study extends React.Component {
- static propTypes = {
- react: PropTypes.string.isRequired,
- vue: PropTypes.string.isRequired
- }
- static defaultProps = {
- // react:"react"
- }
- render() {
- return ( < ul > <li > {
- this.props.react
- } < /li>
- <li>{this.props.vue}</li > </ul>
- )
- }
- }
- let p = {vue:"学习 vue"}
- ReactDOM.render(<Study {...p} / > , document.getElementById("app"))
- </script>
- </body>
- </HTML>
- // 函数式组件 props 校验规则类式组件也可以这么写
- // 在 react 中函数实例化会默认开启严格模式, 严格模式下函数 this 指向 undefined, 函数能接收 props 是因为函数能接收外部传值
- // 函数组件不能初始化 states 和获取 this 上一切属性及方法 (除外部传人的 props)
- <!DOCTYPE HTML>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>
- Document
- </title>
- <script src="https:[email protected]/umd/react.development.js" crossorigin>
- </script>
- <!-- 该文件向外暴露了一个对象 React-Dom -->
- <script src="https:[email protected]/umd/react-dom.development.js" crossorigin>
- </script>
- <script src="https:[email protected]/babel.min.js">
- </script>
- <script src="https:[email protected]/babel.min.js">
- </script>
- <script src="https:[email protected]/prop-types.js">
- </script>
- </head>
- <body>
- <div id="app">
- </div>
- <script type="text/babel">
- function Study(props) {
- return ( < ul > <li > {
- props.react
- } < /li>
- <li>{props.vue}</li > </ul>
- )
- }
- Study.propTypes = {
- react:PropTypes.string.isRequired,
- vue:PropTypes.string.isRequired
- }
- let p = {vue:"学习 vue"}
- ReactDOM.render(<Study {...p} / > , document.getElementById("app"))
- </script>
- </body>
- </HTML>
来源: http://www.bubuko.com/infodetail-3716301.html