React学习11----父组件给子组件传值时defaultProps和propTypes使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaihaohao1/article/details/87889421

都是定义在子组件里面
defaultProps:父子组件传值中,如果父组件调用子组件的时候不给子组件传值,可以在子组件中使用defaultProps定义的默认值

propTypes:验证父组件传值的类型合法性

        1、引入import PropTypes from 'prop-types';

        2、类.propTypes = {
            name: PropTypes.string
        };

参考:
https://reactjs.org/docs/typechecking-with-proptypes.html

例子:项目结构:
在这里插入图片描述

父组件:Father.js

import React from 'react';
import Son from "./Son";

/**
 * 父子组件:组件的相互调用中,我们把调用者称为父组件,被调用者称为子组件
 * 在这里Father.js 是父组件,Son.js是子组件
 *
 * 把父组件的对象传给子组件
 */

class Father  extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            title:'父组件的标题',
            num:123456,
        }
    }
    getData=()=>{
        alert('我是父组件的getData方法')
    }
    setData=()=>{
        alert('我是父组件的setData方法')
    }
    render() {
        return (
            <div>
                {/* 父组件黑子组件传值 */}
                {/*<Son  num = {this.state.num}/>*/}
                <Son title = {this.state.title} num = {this.state.num}/>
            </div>

        );
    }
}
export default Father;

子组件:Son.js

import React from 'react';
import PropTypes from 'prop-types';
/*
父组件给子组件传值:


    defaultProps:父子组件传值中,如果父组件调用子组件的时候不给子组件传值,可以在子组件中使用defaultProps定义的默认值

    propTypes:验证父组件传值的类型合法性

            1、引入import PropTypes from 'prop-types';

            2、类.propTypes = {
                name: PropTypes.string
            };


    都是定义在子组件里面


https://reactjs.org/docs/typechecking-with-proptypes.html


*/

class Son extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            name : '子组件',
        }
    }

    render() {
        return(

            <div>
                {/* 接收父组件传过来的属性 */}
                {this.props.title}
                <br/><br/>
                {this.props.num}
                <br/><br/>

            </div>
        );
    }
}//class

//defaultProps   如果父组件调用子组件的时候不给子组件传值,可以在子组件中使用defaultProps定义的默认值
//父组件中 <Son  num = {this.state.num}/> 没有定义 title 属性传值时,设置默认值
Son.defaultProps={

    title:'标题'
}

//同行propTypes定义父组件给子组件传值的类型
//指定 num 是 number 类型,父类中传别的类型的值,浏览器会有警告
Son.propTypes={

    num:PropTypes.number
}
export default Son;

ok完了
源码下载:
https://download.csdn.net/download/zhaihaohao1/10980372
rdemo11

猜你喜欢

转载自blog.csdn.net/zhaihaohao1/article/details/87889421