React 基礎:先別急著學 React


快速截取重點

這一章節會先學到 React 的三個重要名詞:

  • component
  • props
  • state

資料 vs 畫面(UI)

同樣的資料,可以有不同的畫面(呈現方式)。以新增 todo 為例:

  • 新增 todo 時,同時改變資料與畫面。(有可能資料或畫面不一致)
let id = 0
let todos = []

$('.list').on('click', '.list-item__mark', function(e) {
    const id = Number($item.parent().parent().attr('data-id'))
    todos = todos.map(todo => { // 1. 是要找的 2. 不是要找的
        if (todo.id !== id) {
            return todo
        }
        return {
            ...todo,
            isCompleted: !todo.isCompleted
        }
    })
    setData();          
})
  • 新增 todo 時,改變畫面,再放進資料。
    使用者新增資料,直接改變畫面,然後再從從 UI 畫面裡面,取出資料
$('.btn-dump').click(() => {
    $('.todo').each(function() {
        console.log($(this).text())
    })
})

---
注意:this 與 箭頭函式的關係
  • 新增 todo 時,改變資料,再放進畫面。(React 重要觀念:畫面永遠由 state 產生,UI = f(state),畫面由資料產生)
let state = {
    tosos: [],
}

// state => UI
function render() {
    $('.todos').empty()
    $('.todos').append(
        state.todos.map(todo => Todo(todo)).join('')
}

初次認識 Component

Component 又稱元件、組件。從網頁開發的角度,Component 就像是切版,一塊一塊切割出來之後,進行設計,再組合成一個網頁。

每個 Component 都是一個能夠自成一個功能的區塊,並考量到「重用性」

  • 實作 component 的概念(以 Button 為例)
function Button(callName, content) {
    return `
        <button class="list-item__mark ${className}">${content}</button>`
}
  • 若是傳入參數太多,可以改成傳入一個物件(可讀性提高)
function Button(props) {
    return `
        <button class="list-item__mark ${props.className}">${props.content}</button>`
}

額外參考:web component

React 是什麼?

A JavaScript library for building user interfaces
用來實作使用者界面的 JavaScript 函式庫

2013年誕生,Facebook 所開源出來的函式庫。嚴格來說 React 並不是一個框架,但搭配其他各種 React 生態系成員,其實就算是一個框架。

不如直接來寫看看 React!

建置環境前,先來使用 online IDE:codesandbox

提問 1:不是在寫 JS 嗎?怎麼又把 HTML 寫進 React?
這樣的寫法稱為 JSX,背後透過 babal 轉成 JS function。

import React from "react";
import ReactDOM from "react-dom";

function Hello(props) {
  return <h1>hello, {props.name}</h1>
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Hello name="SC" />, rootElement);

提問 2:之前有提到 component,程式碼長什麼樣子?
寫法就像是 function。透過 React 就能定義自己的 component。

function Hello(props) {
  return <h1>hello, {props.name}</h1>
}
// Hello() 就是一個自定義的 component
// 可以接受參數(要加上 {} <=在裡面程式碼)
function Hello({ children, n}) {
  return <h1>{n} hello, {children}</h1>
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Hello n={1}>
    yoyoyo
  </Hello>, rootElement);

提問 3:那 state 呢?
改變資料(state),UI 也跟著改變。
當 state 更新的時候,React 會重新呼叫 Counter(),拿到 return 的東西,在放在畫面上。

function Counter() {
  const [value, setValue] = React.useState(1)
  function handleClick() {
    setValue(value + 1)
  }
  return <h1 onClick={handleClick}>{value}</h1>
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Counter />, rootElement);

提問 4:JSX 可以預防 XSS 的攻擊嗎?
現代框架大部分有內建自動 escape 的功能。

  • JSX Prevents Injection Attacks
    It is safe to embed user input in JSX:
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;
  • 注意 ,click-based XSS
    針對輸入的 value 進行編碼
<a href={window.encodeURIComponent(todo.content)}>click me</a>







你可能感興趣的文章

F2E合作社|在HTML中設置錨點的三種方式

F2E合作社|在HTML中設置錨點的三種方式

HTTP 常用 method

HTTP 常用 method

Robot Framework之第一個helloworld練習題

Robot Framework之第一個helloworld練習題






留言討論