react: 三大屬性之pros


1. 簡介

  • pros用於接收傳入組件的屬性信息
  • 一般pros只用於讀取,不能修改,修改pros代碼會直接報錯

2. 基本使用

//創建組件

class Person extends React.Component{

	constructor(props){
		//構造器是否接收props,是否傳遞給super,取決於:是否希望在構造器中通過this訪問props
		// console.log(props);
		super(props)
		console.log('constructor',this.props);
	}

	render(){
            return (<div></div>)
        }
}
//渲染組件到頁面
ReactDOM.render(<Person name="jerry" age={19}  sex="男"/>,document.getElementById('test1'))

const p = {name:'老劉',age:18,sex:'女'}
ReactDOM.render(<Person {...p}/>,document.getElementById('test2'))
// 上面的..p寫法將p對象展開並傳入到Person組件,將對象的屬性名作為key,屬性值作為value傳入到Person組件,效果相當於下面的寫法
ReactDOM.render(<Person name={p.name} age={p.age} sex={p.sex}/>,document.getElementById('test3'))

3. 限制pros的參數類型

通過類名.propTypes, 類名.defaultProps 給類自身添加屬性限制信息

      //創建組件
        class Person extends React.Component{
		render(){
                  return (<div></div>)
                }
        }

	//對標簽屬性進行類型、必要性的限制
	Person.propTypes = {
		name:PropTypes.string.isRequired, //限制name必傳,且為字符串
		sex:PropTypes.string,//限制sex為字符串
		age:PropTypes.number,//限制age為數值
		speak:PropTypes.func,//限制speak為函數
	}
	//指定默認標簽屬性值
	Person.defaultProps = {
		sex:'男',//sex默認值為男
		age:18 //age默認值為18
	}
}

4. 限制pros的參數類型的簡寫方式

在類中,在屬性前加上static表示給類自身添加屬性,而不是給實例添加屬性

	class Person extends React.Component{

		constructor(props){
			//構造器是否接收props,是否傳遞給super,取決於:是否希望在構造器中通過this訪問props
			// console.log(props);
			super(props)
			console.log('constructor',this.props);
		}

		//對標簽屬性進行類型、必要性的限制
		static propTypes = {
			name:PropTypes.string.isRequired, //限制name必傳,且為字符串
			sex:PropTypes.string,//限制sex為字符串
			age:PropTypes.number,//限制age為數值
		}

		//指定默認標簽屬性值
		static defaultProps = {
			sex:'男',//sex默認值為男
			age:18 //age默認值為18
		}
		
		render(){
                  return (<div></div>)
                }
	 }


免責聲明!

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



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