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

Javascript 基于类的组件与功能组件有什么区别(Reactjs),javascript,reactjs,Javascript,Reactjs,我对React不熟悉,我想清楚该使用哪一种,当涉及到组件时,我发现有两种类型 功能组件: import React from 'react' const userInput = (props) => { return( <div> <input type='text' onChange={props.nameChanged} value={props.username}></input>

我对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;
从“React”导入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;
import React,{Component}来自'React';
导入“/App.css”;
从“./UserOutput/UserOutput”导入UserOutput;
从“./UserInput/UserInput”导入UserInput;
类应用程序扩展组件{
render(){
返回(
分配输出:
  • 欢迎反应!
); } } 导出默认应用程序;
我读到我们应该总是尝试使用功能组件,因为它在某些事情上有帮助,并且听说我们应该尽可能避免使用基于类的组件

我搞不清楚哪个是对的,哪个不是

为什么要尽可能使用功能组件,好处是什么


我们什么时候应该选择功能组件,什么时候不应该,还不清楚。

分类组件

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

  • 正如您在给出的示例中所看到的,上面的类组件从React.Component扩展而来

  • 在这里,您必须使用这个关键字来访问在类组件中声明的道具和函数

功能组件

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

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

  • 更准确地说,这些基本上是类中的渲染函数 组成部分

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


@RIYAJKHAN谢谢,这确实回答了我的问题。我再次在“谢谢”中找到了问题的答案。请参阅此链接