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