React 最常用的函式(備忘查詢)

介紹

React 是一個用於構建使用者介面的 JavaScript 庫。

React 官方文件

(reactjs。org)

Styled Components 備忘清單

(jaywcjlove。github。io)

import {createRoot} from ‘react-dom/client’import App from ‘。/App’

const elm = document。getElementById(‘app’)const root = createRoot(elm);root。render();

快速建立React專案 (CRA)

npx create-react-app my-app

匯入多個匯出

import React, {Component} from ‘react’import ReactDOM from ‘react-dom’

export class Hello extends Component { 。。。}export default function World() { /* 。。。 */}

使用 export 匯出

Hello

,export default 匯出

World

元件

import World, { Hello } from ‘。/hello。js’;

使用 import 匯入 Hello 元件,在示例中使用。

React 元件中的 CSS

import React from “react”;import “。/Student。css”;export const Student = (

);

注意:類屬性 className

const divStyle = { backgroundImage: ‘url(’ + imgUrl + ‘)’,};export const Student = (

);

屬性

函式元件 Student 中訪問屬性

function Student(props) { return

Hello, {props。name}

;}

Class 元件 Student 中訪問屬性

class Student extends React。Component { render() { return (

Hello, {this。props。name}

); }}

class 元件使用 this。props 訪問傳遞給元件的屬性。

Children

function Example() { return (

您有待處理的通知

)}

函式 AlertBox 元件

function AlertBox(props) { return (

{props。children}
);}

{props。children}

Class AlertBox 元件,與函式元件 AlertBox 元件相同

class AlertBox extends React。Component { render () { return (

{this。props。children}
); }}

{this。props。children}

children 作為子元件的的屬性傳遞。

State

函式中的 State,Hook 是 React 16。8 的新增特性

import { useState } from ‘react’;function Student() { const [count, setCount] = useState(0); const click = () => setCount(count + 1); return (

您點選了 {count} 次

);}

使用 setState 更新狀態,下面是函式元件讀取狀態

您點選了 {count} 次

Class 中的 State

import React from ‘react’;class Student extends React。Component { constructor(props) { super(props); this。state = {count: 1}; // 確保函式可以訪問元件屬性(ES2015) this。click = this。click。bind(this); } click() { const count = this。state。count; this。setState({ count: count + 1}) } render() { return (

您點選了{this。state。count}次

); }}

使用 setState 更新狀態,class 元件中不能使用

hooks

。下面是 class 元件讀取狀態

您點選了{this。state。count}次

迴圈

const elm = [‘one’, ‘two’, ‘three’];function Student() { return (

    {elm。map((value, index) => (
  • {value}
  • ))}
);}

key 值在兄弟節點之間必須唯一

事件監聽

export default function Hello() { function handleClick(event) { event。preventDefault(); alert(“Hello World”); } return ( Say Hi );}

函式注入

function addNumbers(x1, x2) { return x1 + x2;}const element = (

{addNumbers(2, 5)}
);

巢狀

import { useState } from ‘react’import Avatar from ‘。/Avatar’;import Profile from ‘。/Profile’;function Student() { const [count, setCount] = useState(0); return (

);}

Portals

React 並_沒有_建立一個新的 div。它只是把子元素渲染到 domNode 中。domNode 是一個可以在任何位置的有效 DOM 節點。

render() { return ReactDOM。createPortal( this。props。children, domNode );}

提供了一種將子節點渲染到存在於父元件以外的 DOM 節點的優秀的方案

Fragment

import { Fragment } from ‘react’import Avatar from ‘。/Avatar’;import Profile from ‘。/Profile’;const Student = () => ( );

從 v16。2。0 開始 Fragment 可用於返回多個子節點,而無需向 DOM 新增額外的包裝節點。或者使用 <> 效果是一樣的。

const Student = () => ( <> );

檢視: Fragments & strings

返回字串

render() { return ‘Look ma, no spans!’;}

您可以只返回一個字串。檢視: Fragments & strings

返回陣列

const Student = () => [

  • First item
  • Second item
  • ];

    不要忘記 key!檢視: Fragments & strings

    Refs 轉發

    const FancyButton = React。forwardRef( (props, ref) => ( ));

    使用

    // 你可以直接獲取 DOM button 的 ref:const ref = React。createRef(); 點選我

    Class 元件內部使用 ref 屬性

    import {Component,createRef} from ‘react’class MyComponent extends Component { constructor(props) { super(props); this。myRef = createRef(); } render() { return

    ; }}

    提示:Refs 適用於類元件,但不適用於函式元件(除非您使用 useRef hook,請參閱hooks)

    函式元件內部使用 ref 屬性

    function CustomTextInput(props) { // 這裡必須宣告 $input,這樣 ref 才可以引用它 const $input = useRef(null); function handleClick() { $input。current。focus(); } return (

    );}

    嚴格模式 StrictMode

    識別不安全的生命週期

    關於使用過時字串 ref API 的警告

    關於使用廢棄的 findDOMNode 方法的警告

    檢測意外的副作用

    檢測過時的 context API

    確保可複用的狀態

    突出顯示應用程式中潛在問題的工具。請參閱:嚴格模式

    Profiler

    測量一個 React 應用多久渲染一次以及渲染一次的 代價

    為了分析 Navigation 元件和它的子代。應該在需要時才去使用它。

    id(string)

    發生提交的 Profiler 樹的 id

    onRender(function)

    元件樹任何元件 “提交” 一個更新的時候呼叫這個函式

    onRender 回撥函式

    phase: “mount” | “update”

    判斷是由 props/state/hooks 改變 或 “第一次裝載” 引起的重渲染

    actualDuration: number

    本次更新在渲染 Profiler 和它的子代上花費的時間

    baseDuration: number

    在 Profiler 樹中最近一次每一個元件 render 的持續時間

    startTime: number

    本次更新中 React 開始渲染的時間戳

    commitTime: number

    本次更新中 React commit 階段結束的時間戳

    interactions: Set

    當更新被制定時,“interactions” 的集合會被追蹤

    預設值

    Class 元件預設 props

    class CustomButton extends React。Component { // 。。。}CustomButton。defaultProps = { color: ‘blue’};

    使用

    不傳值 props。color 將自動設定為 blue

    Class 元件預設 state

    class Hello extends Component { constructor (props) { super(props) this。state = { visible: true } }}

    在構造 constructor()中設定預設狀態。

    class Hello extends Component { state = { visible: true }}

    函式元件預設 props

    function CustomButton(props) { const { color = ‘blue’ } = props; return

    {color}
    }

    函式元件預設 state

    function CustomButton() { const [color, setColor]=useState(‘blue’) return

    {color}
    }

    JSX

    介紹

    JSX 僅僅只是 React。createElement(component, props, 。。。children) 函式的語法糖

    點選我

    會編譯為

    React。createElement( MyButton, {color: ‘blue’, shadowSize: 2}, ‘點選我’);

    沒有子節點

    會編譯為

    React。createElement( ‘div’, {className: ‘sidebar’})

    JSX 點語法

    const Menu = ({ children }) => (

    {children}
    );Menu。Item = ({ children }) => (
    {children}
    ); 選單一 選單二

    JSX Element

    let element =

    Hello, world!

    ;let emptyHeading =

    ;const root = ReactDOM。createRoot( document。getElementById(‘root’));const element =

    Hello, world

    ;root。render(element);

    參考:渲染元素

    JSX 屬性

    const avatarUrl = “img/picture。jpg”const element = React 最常用的函式(備忘查詢);const element = ( );

    注意:類屬性 className

    JSX 表示式

    let name = ‘張三’;let element =

    Hello, {name}

    ;function fullName(firstName, lastName) { return firstName + ‘ ’ + lastName;}let element = (

    Hello, {fullName(‘三’, ‘張’)}

    );

    JSX style

    const divStyle = { color: ‘blue’, backgroundImage: ‘url(’ + imgUrl + ‘)’,};function MyComponent() { return

    元件
    ;}

    JSX dangerouslySetInnerHTML

    const markup = {__html: ‘我 · 你’ };const MyComponent = () => (

    );

    dangerouslySetInnerHTML 是 React 為瀏覽器 DOM 提供 innerHTML 的替換方案。

    JSX htmlFor

    const MyComponent = () => (

    );

    for 在 JS 中是保留字,JSX 元素使用了 htmlFor 代替

    JSX defaultValue

    非受控元件的屬性,設定元件第一次掛載時的 value