学习React(6) - Class 组件(Component)

博主将继续学习React, 如果用class 这个关键字来做组件的话,应该如何来实现呢!之前是在App.js 文件里用class component, 现在就不在App.js 文件里实现。

就直接上代码,还是一样在src文件夹里,创建一个文件:

// 这是Testclasscomponent.js 文件
// 使用Class Component来写的
import React, {Component} from 'react';

class Testclass extends Component{
    render(){
        return <h1>Test Class component</h1>
    }
} 

export default Testclass;

或者,也可以用functional component 来写:

// 这是Testclasscomponent.js 文件
// 使用functional Component来写的
import React from 'react';

function Testclass(){
    return <h1>Test Class component</h1>
}

export default Testclass;

或者可以使用JSX格式来写:

// 这是Testclasscomponent.js 文件
// 使用 JSX 格式来写的
import React from 'react';

const Testclass = () => {
    return(
        <div>
            <h1>Test Class component</h1>
        </div>
    )
} 

export default Testclass;

或者可以使用 非JSX 格式来写,只是这个写法看起来有点不那么友好:

// 这是Testclasscomponent.js 文件
// 使用 非 JSX 格式来写的
import React from 'react';

const Testclass = () => {
   return React.createElement(
        'div',
        null, // 这个就类似div 的CSS属性,<div id="testOne" className="test">
        // 如果有属性的话,就得这么写:{id:'testOne', className: 'test' },
        React.createElement('h1',null,'Test Class component')
    )
} 

export default Testclass;

在App.js 文件里,应该如何用呢,还是跟以前一样。

import React from 'react';

import './App.css';

import Testclass from './Testclasscomponent';

function App() {
  return (
    <div className="App">
      <Testclass/>
    </div>
  );
}

export default App;

结果如下:
在这里插入图片描述

这问题来了,都可以用class componentfunctional component来表示,它们之间有什么优缺点呢?
Functional components are simple functions receiving props and returning a declaration. Use functional components as much as possible.
The first advantage of functional component: Absence of “this” keyword which you will encounter in a class-based component. “this” keyword can be quite tricky for a beginner and functional component will help you in that aspect.
The second advantage of functional component: You will be forced to think of a solution without having to use state if you have a number of components each with their own private state maintenance and debugging your application is kind of difficult.
The third advantage of functional component: Functional components tend to be without any complicated logic and are mainly responsible for the user interface (UI). This is why functional components are also called stateless components, dump components or presentational components.

Class components are a bit more feature-rich. They can maintain their own private data also called as state. They can contain complicated UI logic and most importantly they provide lifecycle hooks. Class components are also called as stateful components, smart components, or container components.

如果觉得不错,就给个赞吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章