Lembaran Penipuan React: Edisi Komponen Fungsian

PHPz
Lepaskan: 2024-08-07 01:00:33
asal
657 orang telah melayarinya

React Cheat Sheet: Functional Components Edition

React Cheat Sheet

React has evolved significantly since its inception, and with the rise of Hooks, functional components have become the go-to approach for building React applications. This cheat sheet provides an overview of the key concepts, features, and best practices for using functional components in React.

1. Functional Components Basics

A functional component is a plain JavaScript function that returns a React element.

const MyComponent = () => { return 
Hello, World!
; };
Salin selepas log masuk

2. Using JSX

JSX is a syntax extension that allows you to write HTML-like code within your JavaScript.

const MyComponent = () => { return ( 

Welcome to React

); };
Salin selepas log masuk

3. Props

Props are used to pass data from a parent component to a child component.

const Greeting = ({ name }) => { return 

Hello, {name}!

; }; // Usage
Salin selepas log masuk

4. Default Props

You can define default props for a component.

const Greeting = ({ name = "Guest" }) => { return 

Hello, {name}!

; };
Salin selepas log masuk

5. State with useState

The useState Hook allows you to add state to functional components.

import { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( 

Count: {count}

); };
Salin selepas log masuk

6. Effect Hook: useEffect

The useEffect Hook lets you perform side effects in functional components.

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 
Data fetched. Check console.
; };
Salin selepas log masuk

7. Conditional Rendering

Render different UI elements based on certain conditions.

const LoginMessage = ({ isLoggedIn }) => { return ( 
{isLoggedIn ?

Welcome back!

:

Please log in.

}
); };
Salin selepas log masuk

8. Lists and Keys

Render lists of data and use keys to help React identify which items have changed.

const ItemList = ({ items }) => { return ( 
    {items.map(item => (
  • {item.name}
  • ))}
); };
Salin selepas log masuk

9. Event Handling

Handle events in functional components.

const Button = () => { const handleClick = () => { alert('Button clicked!'); }; return ; };
Salin selepas log masuk

10. Forms and Controlled Components

Handle form input with controlled components.

const Form = () => { const [value, setValue] = useState(''); const handleChange = (e) => { setValue(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); alert(`Submitted value: ${value}`); }; return ( 
); };
Salin selepas log masuk

11. Context API

Use the Context API for state management across the component tree.

import { createContext, useContext } from 'react'; const MyContext = createContext(); const MyProvider = ({ children }) => { const value = 'Hello from context'; return (  {children}  ); }; const MyComponent = () => { const contextValue = useContext(MyContext); return 
{contextValue}
; };
Salin selepas log masuk

12. Custom Hooks

Create reusable logic with custom hooks.

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 
{data ? JSON.stringify(data) : 'Loading...'}
; };
Salin selepas log masuk

13. Memoization with useMemo

Optimize performance by memoizing expensive calculations.

import { useMemo } from 'react'; const ExpensiveComponent = ({ number }) => { const expensiveCalculation = useMemo(() => { // Assume this is a computationally expensive operation return number * 2; }, [number]); return 
{expensiveCalculation}
; };
Salin selepas log masuk

14. useCallback

Use useCallback to memoize functions to prevent unnecessary re-renders.

import { useCallback } from 'react'; const Button = ({ onClick }) => { return ; }; const ParentComponent = () => { const handleClick = useCallback(() => { console.log('Button clicked'); }, []); return 
Salin selepas log masuk

15. useReducer

Manage complex state logic with the 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 ( 

Count: {state.count}

); };
Salin selepas log masuk

16. Fragments

Use fragments to group multiple elements without adding extra nodes to the DOM.

const MyComponent = () => { return ( <> 

Title

Description

); };
Salin selepas log masuk

17. Portals

Render children into a DOM node outside the parent component's DOM hierarchy.

import { createPortal } from 'react-dom'; const Modal = ({ children }) => { return createPortal( 
{children}
, document.getElementById('modal-root') ); };
Salin selepas log masuk

18. Error Boundaries with Error Boundary Component

Use class components for error boundaries.

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 

Something went wrong.

; } return this.props.children; } } // Usage
Salin selepas log masuk

19. Lazy Loading with React.lazy and Suspense

Dynamically import components to reduce the initial load time.

import { lazy, Suspense } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); const App = () => { return ( Loading...
}> ); };
Salin selepas log masuk

20. PropTypes for Type Checking

Use prop-types to document and enforce component prop types.

import PropTypes from 'prop-types'; const Greeting = ({ name }) => { return 

Hello, {name}!

; }; Greeting.propTypes = { name: PropTypes.string.isRequired, };
Salin selepas log masuk

Functional components offer a clean and straightforward way to build React applications, especially with the powerful capabilities introduced by Hooks. This cheat sheet provides a quick reference to essential concepts, helping you write effective and efficient React code.

Atas ialah kandungan terperinci Lembaran Penipuan React: Edisi Komponen Fungsian. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!