函数组件 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> ) }
展示型组件和容器型组件是可以互相嵌套的,展示型组件的子组件既可以包含展示型组件,也可以包含容器型组件,容器型组件也是如此。例如,当一个容器型组件承担的数据管理工作过于复杂时,可以在它的子组件中定义新的容器型组件,由新组件分担数据的管理。展示型组件和容器型组件的划分完全取决于组件所做的事情。
总结
新闻热点
疑难解答
图片精选