首頁 > web前端 > js教程 > 主體

React 備忘單:功能組件版

PHPz
發布: 2024-08-07 01:00:33
原創
746 人瀏覽過

React Cheat Sheet: Functional Components Edition

反應備忘錄

React 自誕生以來已經發生了顯著的發展,隨著 Hooks 的興起,函數式元件已成為建立 React 應用程式的首選方法。本備忘單概述了在 React 中使用函數式元件的關鍵概念、功能和最佳實踐。

1. 功能組件基礎知識

函數式元件是一個傳回 React 元素的普通 JavaScript 函數。

const MyComponent = () => {
  return <div>Hello, World!</div>;
};
登入後複製

2. 使用 JSX

JSX 是一種語法擴展,可讓您在 JavaScript 中編寫類似 HTML 的程式碼。

const MyComponent = () => {
  return (
    <div>
      <h1>Welcome to React</h1>
    </div>
  );
};
登入後複製

3.道具

Props 用於將資料從父元件傳遞到子元件。

const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

// Usage
<Greeting name="Alice" />
登入後複製

4.預設道具

您可以為元件定義預設屬性。

const Greeting = ({ name = "Guest" }) => {
  return <h1>Hello, {name}!</h1>;
};
登入後複製

5. 狀態與 useState

useState Hook 允許您為功能組件新增狀態。

import { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};
登入後複製

6.效果掛鉤:useEffect

useEffect Hook 可讓您在功能元件中執行副作用。

import { useEffect } from 'react';

const DataFetcher = () => {
  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => console.log(data));
  }, []); // Empty dependency array means it runs once

  return <div>Data fetched. Check console.</div>;
};
登入後複製

7. 條件渲染

依照特定條件渲染不同的UI元素。

const LoginMessage = ({ isLoggedIn }) => {
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
    </div>
  );
};
登入後複製

8. 列表和鍵

渲染資料清單並使用鍵來幫助 React 識別哪些項目已變更。

const ItemList = ({ items }) => {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};
登入後複製

9. 事件處理

處理功能組件中的事件。

const Button = () => {
  const handleClick = () => {
    alert('Button clicked!');
  };

  return <button onClick={handleClick}>Click Me</button>;
};
登入後複製

10. 表格和受控組件

使用受控元件處理表單輸入。

const Form = () => {
  const [value, setValue] = useState('');

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Submitted value: ${value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={value} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
};
登入後複製

11. 上下文API

使用 Context API 跨元件樹進行狀態管理。

import { createContext, useContext } from 'react';

const MyContext = createContext();

const MyProvider = ({ children }) => {
  const value = 'Hello from context';

  return (
    <MyContext.Provider value={value}>
      {children}
    </MyContext.Provider>
  );
};

const MyComponent = () => {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;
};
登入後複製

12. 自訂掛鉤

使用自訂掛鉤建立可重複使用邏輯。

import { useState, useEffect } from 'react';

const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then(response => response.json())
      .then(data => setData(data));
  }, [url]);

  return data;
};

// Usage
const DataComponent = () => {
  const data = useFetch('/api/data');

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};
登入後複製

13. 使用 useMemo 進行記憶

透過記憶昂貴的計算來優化表現。

import { useMemo } from 'react';

const ExpensiveComponent = ({ number }) => {
  const expensiveCalculation = useMemo(() => {
    // Assume this is a computationally expensive operation
    return number * 2;
  }, [number]);

  return <div>{expensiveCalculation}</div>;
};
登入後複製

14. 使用回調

使用 useCallback 來記憶函數以防止不必要的重新渲染。

import { useCallback } from 'react';

const Button = ({ onClick }) => {
  return <button onClick={onClick}>Click me</button>;
};

const ParentComponent = () => {
  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

  return <Button onClick={handleClick} />;
};
登入後複製

15. 使用Reducer

使用 useReducer Hook 管理複雜的狀態邏輯。

import { useReducer } from 'react';

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
};

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
};
登入後複製

16. 碎片

使用片段將多個元素分組,而無需在 DOM 中新增額外的節點。

const MyComponent = () => {
  return (
    <>
      <h1>Title</h1>
      <p>Description</p>
    </>
  );
};
登入後複製

17. 入口網站

將子元件渲染到父元件 DOM 層次結構以外的 DOM 節點。

import { createPortal } from 'react-dom';

const Modal = ({ children }) => {
  return createPortal(
    <div className="modal">
      {children}
    </div>,
    document.getElementById('modal-root')
  );
};
登入後複製

18. 帶有誤差邊界分量的誤差邊界

使用類別組件作為錯誤邊界。

import { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>
登入後複製

19. 使用 React.lazy 和 Suspense 進行延遲加載

動態導入元件以減少初始載入時間。

import { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

const App = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
};
登入後複製

20. 用於類型檢查的 PropTypes

使用 prop-types 來記錄和強制執行組件 prop 類型。

import PropTypes from 'prop-types';

const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

Greeting.propTypes = {
  name: PropTypes.string.isRequired,
};
登入後複製

函數式元件提供了一種乾淨、直接的方式來建立 React 應用程序,尤其是 Hooks 引入的強大功能。此備忘單提供了基本概念的快速參考,幫助您編寫有效且高效的 React 程式碼。

以上是React 備忘單:功能組件版的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!