zoukankan      html  css  js  c++  java
  • react的propTypes和defaultProps

    1.propTypes  

    子组件规定父组件传过来的值的类型  注意下面注释的地方

    import React, { Component } from 'react';
    import PropTypes from 'prop-types'  // PropTypes  首字母大写
    class Child extends Component {
        constructor(props) {
            super(props);
            this.state = {  }
        }
        render() { 
            return ( 
                <div>
                    child
                    {this.props.test}
                    </div>
             );
        }
    }
    // 这个propTypes 是驼峰
     Child.propTypes = {
         // 这个PropTypes 首字母大写
         test: PropTypes.string
     }
    
    export default Child;

    2. defaultProps 

    规定父组件传过来的默认值,如果父组件不传这个值,子组件会使用这个默认值

    子组件:

    import React, { Component } from 'react';
    class Child extends Component {
        constructor(props) {
            super(props);
            this.state = {  }
        }
        render() { 
            return ( 
                <div>
                    child
                    {/* 默认值 sss */}
                   { this.props.testname}   
                </div>
             );
        }
    }
    
     Child.defaultProps = {
         testname:'sssss'
     }
    export default Child;

    父组件:

    import React, { Component } from 'react';
    import Child from './Child'
    class Parent extends Component {
        constructor(props) {
            super(props);
            this.state = { 
                pdata:'父数据'
             }
        }
        render() { 
            return ( 
                <div>
                    {/* 父组件没有传testname */}
                    <Child></Child>
                </div>
             );
        }
    }
     
    export default Parent;
  • 相关阅读:
    php生成二维码
    赞的算法
    Linux系统信息查看命令大全
    详细介绍Linux telnet命令的使用
    Linux VSFTP服务器
    禁止浏览器缓存页面的方法
    php开启短标签
    BZOJ2648 SJY摆棋子(KD-Tree)
    KD-Tree学习笔记
    BZOJ5461 PKUWC2018Minimax(概率期望+线段树合并+动态规划)
  • 原文地址:https://www.cnblogs.com/luguankun/p/13963811.html
Copyright © 2011-2022 走看看