函數組件 vs 類組件
函數組件(Functional Component )和類組件(Class Component),劃分依據是根據組件的定義方式。函數組件使用函數定義組件,類組件使用ES6 class定義組件
// 函數組件function Welcome(props) { return <h1>Hello, {props.name}</h1>;}// 類組件class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; }}無狀態組件 vs 有狀態組件
函數組件一定屬于無狀態組件 (劃分依據是根據組件內部是否維護state)
// 無狀態組件class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; }}// 有狀態類組件class Welcome extends React.Component { constructor(props) { super(props); this.state = { show: true } } render() { const { show } = this.state; return ( <> { show && <h1>Hello, {this.props.name}</h1> } </> ) }}展示型組件 vs 容器型組件
展示型組件(Presentational Component)和容器型組件(Container Component),劃分依據是根據組件的職責。 (展示型組件一般是無狀態組件,不需要state)
class UserListContainer extends React.Component{ constructor(props){ super(props); this.state = { users: [] } } componentDidMount() { var that = this; fetch('/path/to/user-api').then(function(response) { response.json().then(function(data) { that.setState({users: data}) }); }); } render() { return ( <UserList users={this.state.users} /> ) }}function UserList(props) { return ( <div> <ul className="user-list"> {props.users.map(function(user) { return ( <li key={user.id}> <span>{user.name}</span> </li> ); })} </ul> </div> ) }展示型組件和容器型組件是可以互相嵌套的,展示型組件的子組件既可以包含展示型組件,也可以包含容器型組件,容器型組件也是如此。例如,當一個容器型組件承擔的數據管理工作過于復雜時,可以在它的子組件中定義新的容器型組件,由新組件分擔數據的管理。展示型組件和容器型組件的劃分完全取決于組件所做的事情。
總結
新聞熱點
疑難解答
圖片精選