一、基於class關鍵字創建組件
最基本的組件結構:
// 如果要使用class定義組件,必須讓自己的組件,繼承自React.Component
class Movie extends React.Component{
// 在組件內部,必須有render函數。作用:渲染當前組件對應的虛擬DOM結構
render(){
// render函數中,必須返回合法的JSX虛擬DOM結構
return <div>這是class創建的Movie組件</div>;
}
}
以上代碼演示瞭如何通過class創建一個最基本的組件。
二、爲class創建的組件傳遞props參數並直接使用this.props來訪問
React07.html代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React07</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/babel" src="components/React07.jsx"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const user = {
name: "David",
age: 24,
gender: "男"
};
ReactDOM.render(
<Person name={user.name} age={user.age}/>,
document.querySelector("#app")
);
</script>
</body>
</html>
React07.jsx代碼:
class Person extends React.Component{
render(){
{/*注意:在class組件內部,this表示當前組件的實例對象*/}
return <div>{this.props.name} --- {this.props.age}</div>;
}
}
運行結果:
由此可見,在class關鍵字創建的組件中,如果想使用外界傳遞過來的props參數,不需接收,直接通過this.props.***訪問即可。
三、介紹class創建的組件中this.state
以下代碼演示了爲class創建的組件添加this.state:
// React07.jsx中的代碼
class Person extends React.Component{
// 構造器
constructor(){
// 由於Person組件繼承了React.Component這個父類,所以自定義的構造器中必須調用super()
super();
// 只有調用了super()以後,才能使用this關鍵字
this.state = {
msg: "Hello, I am state"
}
}
render(){
// 在class創建的組件中,this.state上的數據,都是可讀可寫的
this.state.msg = "I'm changed";
return <div>
{this.props.name} --- {this.props.age}
<h3>{this.state.msg}</h3>
</div>;
}
}
運行結果:
四、介紹有狀態組件和無狀態組件的區別
- 用構造函數創建出來的組件叫做“無狀態組件”【無狀態組件今後用的不多】。
- 用class關鍵字創建出來的組件叫做“有狀態組件”【今後用的最多】。
- 使用function創建的組件,只有props,沒有自己的私有數據和生命週期函數;使用class關鍵字創建的組件,有自己的私有數據(this.state)和生命週期函數。
- 有狀態組件和無狀態組件之間的本質區別就是:有無state屬性和有無生命週期函數。
- 如果一個組件需要有自己的私有數據,則推薦使用class創建的有狀態組件;如果一個組件不需要有私有的數據,則可以使用無狀態組件。React官方說:無狀態組件由於沒有自己的state和生命週期函數,所以運行效率會比有狀態組件稍微高一些。
五、組件中的props和state之間的區別
- 數據來源上:props中的數據都是外界傳遞過來的;state中的數據都是組件私有的(通過Ajax獲取回來的數據,一般都是私有數據)。
- 可讀可寫性:props中的數據都是隻讀的,不能重新賦值;state中的數據都是可讀可寫的。