React 自定義組件的兩種方式:
函數組件和類組件
第一種,函數組件(無狀態,即無私有屬性,state):
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
第二種,類(ES6)組件(有狀態。即有私有屬性,state):
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
一般完整的類組件,示例:
import React, { Component } from "react";
class Hello extends Component {
// 構造函數
constructor(props){
super(props);
// 聲明私有數據 (類似vue中data的作用)
this.state = { msg:'123' }
}
render() {
console.log(this.state) // 打印查看
return (
<div>
{/* 在組件中使用私有數據 */}
<h1>{this.state.msg}</h1>
</div> );
}
}
export default Hello;
什么情況下使用有狀態組件?什么情況下使用無狀態組件?
如果組件內,不需要有私有的數據,即不需要 state,此時,使用函數創建無狀態組件比較合適;
如果組件內,需要有自己私有的數據,即需要 state,則,使用 class 關鍵字 創建有狀態組件比較合適;
組件中的 props 和 state 之間的區別
props 中存儲的數據,都是外界傳遞到組件中的;
props 中的數據,都是只讀的;
state 中的數據,都是組件內私有的;
state 中的數據,都是可讀可寫的;
props 在 有狀態組件 和 無狀態組件中,都有;
state 只有在 有狀態組件中才能使用;無狀態組件中,沒有 state;
關於ES6類的繼承和this以及props的問題,請看:https://www.cnblogs.com/zqblog1314/p/12902707.html