首页  >  文章  >  web前端  >  React 备忘单:功能组件版

React 备忘单:功能组件版

PHPz
PHPz原创
2024-08-07 01:00:33746浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn