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>
    );
  }
}
posted @ 2020-11-26 17:39  北冥雪  阅读(104)  评论(0编辑  收藏  举报