# 简单应用

  • 大型项目,如果你不校验,后期会变的异常混乱,业务逻辑也没办法保证
import PropTypes from "prop-types";
1
FoodItem.propTypes = {
  content: PropTypes.string,
  deleteItem: PropTypes.func,
  index: PropTypes.number,
};
1
2
3
4
5

# 必传值的校验

  • 不传 requireContent 就会报错
FoodItem.propTypes = {
  content: PropTypes.string,
  deleteItem: PropTypes.func,
  index: PropTypes.number,
  requireContent: PropTypes.string.isRequired,
};
1
2
3
4
5
6

# 使用默认值 defaultProps

FoodItem.defaultProps = {
  defaultContent: "我是必填的内容",
};
1
2
3

# 完整子组件代码


 

















 
 
 

 
 
 
 
 
 



import React, { Component } from "react";
import PropTypes from "prop-types";

class FoodItem extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log(this.props.index);
    this.props.deleteFood(this.props.index);
  }

  render() {
    return <li onClick={this.handleClick}>新加的食物+{this.props.content}</li>;
  }
}

FoodItem.defaultProps = {
  avname: "123",
};

FoodItem.propTypes = {
  content: PropTypes.string,
  deleteItem: PropTypes.func,
  index: PropTypes.number,
  requireContent: PropTypes.string.isRequired,
};

export default FoodItem;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
上次更新时间: 11/16/2021, 8:56:17 PM