React 备忘单:功能组件版

react 备忘单:功能组件版

反应备忘单

react 自诞生以来已经发生了显着的发展,随着 hooks 的兴起,函数式组件已成为构建 react 应用程序的首选方法。本备忘单概述了在 react 中使用函数式组件的关键概念、功能和最佳实践。

1. 功能组件基础知识

功能组件是一个返回 react 元素的纯 javascript 函数。

const mycomponent = () => {  return 
hello, world!
;};

2. 使用 jsx

jsx 是一个语法扩展,允许您在 javascript 中编写类似 html 的代码。

const mycomponent = () => {  return (    

welcome to react

);};

3.道具

props 用于将数据从父组件传递到子组件。

57188​​1438247

4.默认道具

您可以为组件定义默认 props。

const greeting = ({ name = "guest" }) => {  return 

hello, {name}!

;};

5. 状态与 usestate

usestate hook 允许您向功能组件添加状态。

import { usestate } from 'react';const counter = () => {  const [count, setcount] = usestate(0);  return (    

count: {count}

);};

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 
data fetched. check console.
;};

7. 条件渲染

根据一定的条件渲染不同的ui元素。

const loginmessage = ({ isloggedin }) => {  return (    
{isloggedin ?

welcome back!

:

please log in.

}
);};

8. 列表和键

渲染数据列表并使用键来帮助 react 识别哪些项目已更改。

const itemlist = ({ items }) => {  return (    
    {items.map(item => (
  • {item.name}
  • ))}
);};

9. 事件处理

处理功能组件中的事件。

const button = () => {  const handleclick = () => {    alert('button clicked!');  };  return ;};

10. 表格和受控组件

使用受控组件处理表单输入。

const form = () => {  const [value, setvalue] = usestate('');  const handlechange = (e) => {    setvalue(e.target.value);  };  const handlesubmit = (e) => {    e.preventdefault();    alert(`submitted value: ${value}`);  };  return (                      );};

11. 上下文api

使用 context api 进行跨组件树的状态管理。

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}
;};

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;};// usageconst datacomponent = () => {  const data = usefetch('/api/data');  return 
{data ? json.stringify(data) : 'loading...'}
;};

13. 使用 usememo 进行记忆

通过记忆昂贵的计算来优化性能。

import { usememo } from 'react';const expensivecomponent = ({ number }) => {  const expensivecalculation = usememo(() => {    // assume this is a computationally expensive operation    return number * 2;  }, [number]);  return 
{expensivecalculation}
;};

14. 使用回调

使用 usecallback 来记忆函数,以防止不必要的重新渲染。

import { usecallback } from 'react';const button = ({ onclick }) => {  return ;};const parentcomponent = () => {  const handleclick = usecallback(() => {    console.log('button clicked');  }, []);  return 

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 (    

count: {state.count}

);};

16. 碎片

使用片段对多个元素进行分组,无需向 dom 添加额外的节点。

const mycomponent = () => {  return (          

title

description

17. 门户网站

将子组件渲染到父组件 dom 层次结构之外的 dom 节点中。

import { createportal } from 'react-dom';const modal = ({ children }) => {  return createportal(    
{children}
, 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 

something went wrong.

; } return this.props.children; }}// usage

19. 使用 react.lazy 和 suspense 进行延迟加载

动态导入组件,减少初始加载时间。

import { lazy, suspense } from 'react';const lazycomponent = lazy(() => import('./lazycomponent'));const app = () => {  return (    <suspense fallback={
loading...
}> );};

20. 用于类型检查的 proptypes

使用 prop-types 来记录和强制执行组件 prop 类型。

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

Hello, {name}!

;};Greeting.propTypes = { name: PropTypes.string.isRequired,};

函数式组件提供了一种干净、直接的方式来构建 react 应用程序,尤其是 hooks 引入的强大功能。此备忘单提供了基本概念的快速参考,帮助您编写有效且高效的 react 代码。

以上就是React 备忘单:功能组件版的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1490090.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
我的第一个拉取请求刚刚被接受!
上一篇 2025年12月19日 12:56:10
如何使用 NCE 考试模拟测试来加强您的准备
下一篇 2025年12月19日 12:56:17

相关推荐

发表回复

登录后才能评论
关注微信