定義
用於接收上層組件傳入的參數的對象!
DEMO
這里是一個簡單的傳值到組件內部的demo:
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> </head> <body> <!--react基礎庫--> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.js"></script> <!--bable轉換庫,ES語法以及Jax語法的轉換--> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <div id="content"></div> <script type="text/babel"> //定義組件 class ComponentA extends React.Component{ //構造函數,在初始化組件的時候會執行 constructor(props){ super(props); //state的值是從props中獲取的上層對象傳入的參數 this.state={ name:this.props.name, age:this.props.age } } //render會進行頁面的渲染,當state中數據更新或者發送ajax等事件被監聽到都會觸發render的刷新 render(){ //從state中取值 const name = this.state.name; const age = this.state.age; return( <div> <p>名字:{name}</p> <p>年齡:{age}</p> </div> ); } } //傳入參數name以及age ReactDOM.render(<ComponentA name={'aaa'} age={20}/>,document.getElementById("content")); </script> </body> </html>
頁面展現效果
調用組件時傳入的參數name以及age在組件內部初始化時被獲取到值,並且在render時被state渲染到頁面上:
擴展
1、默認值:
props中的屬性是可以設置默認值的:
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> </head> <body> <!--react基礎庫--> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.js"></script> <!--bable轉換庫,ES語法以及Jax語法的轉換--> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <div id="content"></div> <script type="text/babel"> //定義組件 class ComponentA extends React.Component{ //構造函數,在初始化組件的時候會執行 constructor(props){ super(props); //state的值是從props中獲取的上層對象傳入的參數 this.state={ name:this.props.name, age:this.props.age } } //render會進行頁面的渲染,當state中數據更新或者發送ajax等事件被監聽到都會觸發render的刷新 render(){ //從state中取值 const name = this.state.name; const age = this.state.age; return( <div> <p>名字:{name}</p> <p>年齡:{age}</p> </div> ); } } //指定默認值 ComponentA.defaultProps = { name:'Jerry', age:30 } //這里我沒有傳任何參數 ReactDOM.render(<ComponentA />,document.getElementById("content")); </script> </body> </html>
頁面顯示效果:
名字:Jerry
年齡:30
2、約束:
給傳入的props添加約束,規范數據類型與添加約束:
官網實例:https://react.docschina.org/docs/typechecking-with-proptypes.html
由於博主版本不對,所以測試編譯報錯,所以了解下就好,使用腳手架搭建的React環境不會存在版本問題。
3、擴展運算符【...】
render(){ //從state中取值 const Student = { name : 'Rose' , level: 100}; const Student2= {...Student}; const array = [1,2,3,4,5]; const array2 = [0, ...array,6] return( <div> <p>名字:{Student2.name}</p> <p>array2:{array2}</p> </div> ); }
渲染結果:
名字:Rose
array2:0123456