學習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.

如果覺得不錯,就給個贊吧!

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