小编典典

基于类的组件与功能性组件有什么区别(Reactjs)

reactjs

我是 React的 新手,我想清楚地知道要使用哪一种,关于组件,我看到有两种类型。

功能组件:

import React from 'react'

const userInput = (props) => {
    return(
        <div>
            <input type='text' onChange={props.nameChanged} value={props.username}></input>
        </div>
    )
};

export default userInput;

基于类的组件:

import React, { Component } from 'react';
import './App.css';
import UserOutput from './UserOutput/UserOutput';
import UserInput from './UserInput/UserInput';

class App extends Component {

  render() {
    return (
      <div className="App">
        <h3>Assignment Output :</h3>
        <ul>
          <li>
            <UserOutput 
            username={this.state.Usernames[0].username}>
            Welcome to React!
            </UserOutput>
            <UserInput 
            nameChanged={this.nameChangedHandler}>
            </UserInput>
          </li>
                      </ul>
      </div>
    );
  }
}

export default App;

我读到我们应该始终尝试使用 功能性组件, 因为它在某些方面有所帮助,并且还听说我们应该尽可能避免使用基于 类的组件

我很困惑哪个是对的,哪个不是。

为什么要尽可能使用功能组件,这样做有什么好处?

我们何时应该选择功能组件,何时不应该,尚不清楚。


阅读 352

收藏
2020-07-22

共1个答案

小编典典

类组件

  • 基于类的组件使用ES6类语法。它可以利用生命周期方法。

  • 如您在示例中所见,您在上面给出的Class组件是从React.Component扩展的。

  • 在这里,您必须使用此关键字来访问在类组件内部声明的道具和功能。

功能组件

  • 与基于类的函数相比,功能组件更简单。

  • 功能组件主要关注应用程序的UI,而不关注行为。

  • 更精确地说,这些基本上是类组件中的render函数。

  • 功能组件不能具有状态,也不能使用生命周期方法。

2020-07-22