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 都會被運行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM