React 从入门到进阶之路(八)

之前的文章我们介绍了 React中的组件、父子组件、React props父组件给子组件传值、子组件给父组件传值、父组件中通过refs获取子组件属性和方法。接下来我们将介绍 React propTypes  defaultProps。

  之前我们已经根据 create-react-app 模块创建了一个 React 项目,并定义 App.js 为根组件,即父组件,Home.js 为子组件。我们看一下两个组件的代码:

App.js

 1 import React, {Component} from 'react';
 2 import Home from './components/Home';
 3 
 4 class App extends Component {
 5     constructor(props) {
 6         super(props);
 7         this.state = {
 8             title: "I am father",
 9             age: 30,
10             info: "I like React",
11         }
12     }
13 
14     render() {
15         return (
16             <div className="App">
17                 <Home title={this.state.title} age={this.state.age}/>
18             </div>
19         );
20     }
21 }
22 
23 export default App;

Home.js

 1 import React, {Component} from 'react';
 2 import PropTypes from 'prop-types';
 3 
 4 class Home extends Component {
 5     constructor(props) {
 6         super(props);
 7         this.state = {
 8             name: "zhangsan",
 9         }
10     }
11 
12     render() {
13         return (
14             <div>
15                 <p>Hello {this.state.name}</p>
16 
17                 {/*父组件将 title 传过来*/}
18                 {/*输出结果:I am father*/}
19                 <p>{this.props.title}</p>
20 
21                 {/*父组件将 age 传过来,在下面的 defaultProps 中再重新定义*/}
22                 {/*父组件将 age 传过来,在下面的 propTypes 定义 age 必须为 number 类型*/}
23                 {/*输出结果:30*/}
24                 <p>{this.props.age}</p>
25 
26                 {/*父组件没有将 info 传过来,在下面的 defaultProps 中定义*/}
27                 {/*输出结果:I like React too*/}
28                 <p>{this.props.info}</p>
29             </div>
30         );
31     }
32 }
33 
34 Home.defaultProps = {
35     age: 60,
36     info: "I like React too",
37 }
38 
39 Home.propTypes = {
40     age: PropTypes.number
41 }
42 
43 export default Home;

在父组件 App.js 中,通过 <Home /> 将子组件 Home 挂载到父组件 App 上,然后将 title 和 age 传递给子组件。

在子组件 Home 中,我们通过 this.props 属性来获取父组件 App 传递过来的值,但是我们在子组件 Home 中定义了一个 defaultProps 属性,并声明了 age 和 info 变量。

在输出结果中我们可以看出:

  如果在子组件的 defaultProps 属性中没有更改父组件传递过来的值,那么将按父组件传递过来的值输出,

  如果在子组件的 defaultProps 属性中更改了父组件传递过来的值,那么还是按父组件传递过来的值输出,

  如果父组件并没有传递过来某值,但是在子组件的 defaultProps 属性中定义了该值,那么将按照定义的值输出。

在子组件 Home 中我们还通过 import PropTypes from ‘prop-types’; 引入了 PropTypes 模块,并定义了一个 propTypes 属性定义了一个 age: PropTypes.number 的约束,那么如果父组件传递过来的 age 如果不是 number 类型的话,则会在控制台报错。

结论:

defaultProps:父子组件传值中,如果父组件调用子组件的时候不给子组件传值,可以在子组件中使用defaultProps定义的默认值
propTypes:验证父组件传值的类型合法性

最后的结果为:

原文地址:https://www.cnblogs.com/weijiutao/p/10652902.html