iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
Modern Web

30天學 React.js 系列 第 6

[Day6] [筆記] React Component (下)

前言

昨天我們知道 Component 是什麼,與其優點。那我們今天就接續介紹在 Component 中使用表達式、以及如何客製化撰寫 Component

何謂 Declarative 宣告

開始前,我們必須知道在開發 React 元件時,我們主要是用 Declarative 開發思維方式設計程式。
簡單來說 Declarative 宣告 就是用一種抽象方式,程式重點著重在 WHAT TO DO。而非 How

  • Declarative 範例
const array = [1,2,3]
let result = array.filter(function(item){
   // 篩選數字大於 2 的內容
   return item > 2
})
console.log(result); //[3]

我們從範例中可以清楚程式在做什麼事,那接著我們來看與其對應的 Imperative 又是如何撰寫?

  • Imperative範例
const array = [1,2,3];
let result = [];
for(let i =0; i < 3; i ++){
  if(array[i] > 2){
     result.push(array[i])
  }
}
console.log(result); //[3]

從上面程式碼我們可以得知, Imperative 比較著重在程式運算這塊,也就是所謂的 How

這篇寫得很清楚可以直接參考這篇文章 Buzz Word 1 : Declarative vs. Imperative

客製化元件

講完 Declarative 宣告,我們就直接進入主題吧!

Step1.

元件中,我們使用 JSX 語法糖撰寫完成後,我們將函氏當成元件 Export 匯出。

  1. 必須注意元件開頭必須大寫 如: AddComponent
  2. 載入 CSS 時,我們在 JSX 上必須用 className 而非 class
import { Fragment } from "react"; // Fragement 可以讓我們直接產生一個空節點
import "../index.css";

const AddComponent = () => {
    return (
        <Fragment>
            <span>記事:</span>
            <input type="text" className="app" />
            <span>日期:</span>
            <input type="date" className="app" />
            <span>時間:</span>
            <input type="time" className="app" />
            <button className="add">新增</button>
        </Fragment>
    )
}
export default AddComponent;

Step2.

引入其他元件使用

import React from 'react';
import './index.css';
import AddComponent from '../Home/component/Add';
import { Fragment } from 'react';

const boolean = true;
const Home = () => {
  return (
    <Fragment>
      <AddComponent />
      <AddComponent />
      {boolean === true && <AddComponent />} //如果變數 Boolean 為真,就會渲染後方 Component
    </Fragment>
  )
}

export default Home;

Step3.

最後在跟節點, Root 上掛載上去

  1. 元件只能有一個 root element
import React from 'react';
import ReactDOM from 'react-dom';
import Home from './pages/Home';
import { configureStore } from '@reduxjs/toolkit';


ReactDOM.render(
  <Home />,
  document.getElementById('root')
);

參考資料


上一篇
[Day5][筆記] React Component (上)
下一篇
[Day7] [筆記] React Props (上)
系列文
30天學 React.js 14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言