zoukankan      html  css  js  c++  java
  • React 学习(三) 属性验证PropTypes

    propTypes & defaultProps

    import React, { Component } from "react";
    import Proptypes from "prop-types";
    
    // Function
    function ChildCpn(props) {
      const { name, age, height } = props;
      const { names } = props;
    
      return (
        <div>
          <h2>SubComponent:{name + " " + age + " " + height}</h2>
          <div>
            {names.map((item, index) => {
              return <li key={index}>{item}</li>;
            })}
          </div>
        </div>
      );
    }
    
    // Class
    class ChildCpn2 extends Component {
      static propTypes = {};
      static defaultProps = {};
    
      render() {
        const { name, age, height, names } = this.props;
    
        return (
          <div>
            <h2>SubCompnent2:{name + " " + age + " " + height}</h2>
            <div>
              {names.map((item, index) => {
                return <li key={index}>{item}</li>;
              })}
            </div>
          </div>
        );
      }
    }
    
    // Custom Validation Rule
    ChildCpn.propTypes = {
      name: Proptypes.string.isRequired,
      age: Proptypes.number,
      height: Proptypes.number,
      names: Proptypes.array,
    };
    
    ChildCpn2.propTypes = {
      name: Proptypes.string,
      age: Proptypes.number,
      height: Proptypes.number,
      names: Proptypes.array,
    };
    
    // defaultValue
    ChildCpn.defaultProps = {
      name: "HelloKitty",
      age: 30,
      height: 1.78,
      names: ["defalut"],
    };
    
    ChildCpn2.defaultProps = {
      name: "BlackAngel",
      age: 30,
      height: 1.78,
      names: ["defalut"],
    };
    
    export default class App extends Component {
      render() {
        return (
          <div>
            <ChildCpn
              name="Smallstars"
              age={18}
              height={1.83}
              names={["abc", "de"]}
            />
    
            <ChildCpn />
    
            <ChildCpn2 age={18} height={1.83} names={["abc", "de"]} />
          </div>
        );
      }
    }
    
    每天进步一点点
  • 相关阅读:
    php安装扩展的几种方法
    navicat连接linux系统中mysql-错误:10038
    linux下报错bash: service: command not found
    linux配置防火墙和重启防火墙
    linux 环境安装
    匿名函数
    workman的学习总结
    xampp/apache启动失败解决方法
    Linux 查看IP
    慢查询日志
  • 原文地址:https://www.cnblogs.com/smallstars/p/14043537.html
Copyright © 2011-2022 走看看