8. react 基础 - props 默认值和类型限制 与 Props , State , render 函数 关系

一. PropTypes 与 DefaultProps 官方文档

  1. PropTypes 属性校验

    引入 PropTypes

      import PropTypes from 'prop-types';

    强校验 props 属性

    eg:

      import React, { Component } from 'react'

      import PropTypes from 'prop-types'

      class TodoItem extends Component{

        constructor(props){

          super(props);

        }

      }

      // 校验 传递过来的 value 为 string 类型

      // 校验 传递过来的 itemDelete 为 function 类型

      // 校验 传递过来的 index 为 string 类型 并且必须要传递

      // 如果传递的数据不对 会在 控制太报一个警告

      TodoItem.propTypes = {

        value: PropTypes.string,

        itemDelete: PropTypes.func,

        index: PropTypes.string.isRequired

      }

      export default TodoItem;

  2.DefaultProps 设置默认值

    eg:

      import React, { Component } from 'react'

      class TodoItem extends Component{

        constructor(props){

          super(props);

        }

      }

      // 设置 props 的 test默认属性为 hello world

      TodoItem.defaultProps = {

        test: 'hello world'

      }

      export default TodoItem;

二. Props , State , render 函数 关系

  // 当组件 的 props 和 state 发生改变时 render 方法会重新执行

  // 当父组件 的 render 函数被运行时, 子组件 的 render 都会被运行