首页 > 语言 > JavaScript > 正文

深入理解react 组件类型及使用场景

2024-05-06 15:41:51
字体:
来源:转载
供稿:网友

函数组件 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>; }}
    函数组件的写法要比类组件简洁,不过类组件比函数组件功能更加强大。函数组件更加专注和单一,承担的职责也更加清晰,它只是一个返回React 元素的函数,只关注对应UI的展现。函数组件接收外部传入的props,返回对应UI的DOM描述, 类组件可以维护自身的状态变量,即组件的state,类组件还有不同的生命周期方法,可以让开发者能够在组件的不同阶段(挂载、更新、卸载),对组件做更多的控制。

无状态组件 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> ) }

展示型组件和容器型组件是可以互相嵌套的,展示型组件的子组件既可以包含展示型组件,也可以包含容器型组件,容器型组件也是如此。例如,当一个容器型组件承担的数据管理工作过于复杂时,可以在它的子组件中定义新的容器型组件,由新组件分担数据的管理。展示型组件和容器型组件的划分完全取决于组件所做的事情。

总结

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选