React 备忘单:功能组件版

2024-08-07 0 936

React 备忘单:功能组件版

反应备忘单

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

1. 功能组件基础知识

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

1

2

3

const mycomponent = () => {

  return <div>hello, world!</div>;

};

2. 使用 JSx

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

1

2

3

4

5

6

7

const mycomponent = () =&gt; {

  return (

    <div>

      <h1>welcome to react</h1>

    </div>

  );

};

3.道具

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

57188​​1438247

4.默认道具

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

1

2

3

const greeting = ({ name = "guest" }) =&gt; {

  return <h1>hello, {name}!</h1>;

};

5. 状态与 usestate

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

1

2

3

4

5

6

7

8

9

10

11

12

import { usestate } from 'react';

const counter = () =&gt; {

  const [count, setcount] = usestate(0);

  return (

    <div>

      <p>count: {count}</p>

      <button onclick="{()"> setcount(count + 1)}&gt;increment</button>

    </div>

  );

};

6.效果挂钩:useeffect

useeffect hook 可让您在功能组件中执行副作用。

1

2

3

4

5

6

7

8

9

10

11

import { useeffect } from 'react';

const datafetcher = () =&gt; {

  useeffect(() =&gt; {

    fetch('/API/data')

      .then(response =&gt; response.JSON())

      .then(data =&gt; console.log(data));

  }, []); // empty dependency array means it runs once

  return <div>data fetched. check console.</div>;

};

7. 条件渲染

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

1

2

3

4

5

6

7

const loginmessage = ({ isloggedin }) =&gt; {

  return (

    <div>

      {isloggedin ? <h1>welcome back!</h1> : <h1>please log in.</h1>}

    </div>

  );

};

8. 列表和键

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

1

2

const itemlist = ({ items }) =&gt; {

  return (

    {items.map(item => (

  • {item.name}
  • ))}

); };

9. 事件处理

处理功能组件中的事件。

1

2

3

4

5

6

7

const button = () =&gt; {

  const handleclick = () =&gt; {

    alert('button clicked!');

  };

  return <button onclick="{handleclick}">click me</button>;

};

10. 表格和受控组件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

const fORM = () =&gt; {

  const [value, setvalue] = usestate('');

  const handlechange = (e) =&gt; {

    setvalue(e.target.value);

  };

  const handlesubmit = (e) =&gt; {

    e.preventdefault();

    alert(`submitted value: ${value}`);

  };

  return (

); };

11. 上下文api

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import { createcontext, usecontext } from 'react';

const mycontext = createcontext();

const myprovider = ({ children }) =&gt; {

  const value = 'hello from context';

  return (

    <mycontext.provider value="{value}">

      {children}

    </mycontext.provider>

  );

};

const mycomponent = () =&gt; {

  const contextvalue = usecontext(mycontext);

  return <div>{contextvalue}</div>;

};

12. 自定义挂钩

使用自定义挂钩创建可重用逻辑。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import { usestate, useeffect } from 'react';

const usefetch = (url) =&gt; {

  const [data, setdata] = usestate(null);

  useeffect(() =&gt; {

    fetch(url)

      .then(response =&gt; response.json())

      .then(data =&gt; setdata(data));

  }, [url]);

  return data;

};

// usage

const datacomponent = () =&gt; {

  const data = usefetch('/api/data');

  return <div>{data ? json.stringify(data) : 'loading...'}</div>;

};

13. 使用 usememo 进行记忆

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

1

2

3

4

5

6

7

8

9

10

import { usememo } from 'react';

const expensivecomponent = ({ number }) =&gt; {

  const expensivecalculation = usememo(() =&gt; {

    // assume this is a computationally expensive operation

    return number * 2;

  }, [number]);

  return <div>{expensivecalculation}</div>;

};

14. 使用回调

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

1

2

3

4

5

6

7

8

9

10

11

12

13

import { usecallback } from 'react';

const button = ({ onclick }) =&gt; {

  return <button onclick="{onclick}">click me</button>;

};

const parentcomponent = () =&gt; {

  const handleclick = usecallback(() =&gt; {

    console.log('button clicked');

  }, []);

  return <button onclick="{handleclick}"></button>;

};

15. 使用reducer

使用 usereducer hook 管理复杂的状态逻辑。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import { usereducer } from 'react';

const reducer = (state, action) =&gt; {

  switch (action.type) {

    case 'increment':

      return { count: state.count + 1 };

    case 'decrement':

      return { count: state.count - 1 };

    default:

      throw new error();

  }

};

const counter = () =&gt; {

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

  return (

    <div>

      <p>count: {state.count}</p>

      <button onclick="{()"> dispatch({ type: 'increment' })}&gt;increment</button>

      <button onclick="{()"> dispatch({ type: 'decrement' })}&gt;decrement</button>

    </div>

  );

};

16. 碎片

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

1

2

3

4

5

6

7

8

const mycomponent = () =&gt; {

  return (

    

      <h1>title</h1>

      <p>description</p>

    &gt;

  );

};

17. 门户网站

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

1

2

3

4

5

6

7

8

9

10

import { createportal } from 'react-dom';

const modal = ({ children }) =&gt; {

  return createportal(

    <div classname="modal">

      {children}

    </div>,

    document.getelementbyid('modal-root')

  );

};

18. 带有误差边界分量的误差边界

使用类组件作为错误边界。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

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></mycomponent></errorboundary>

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

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

1

2

3

4

5

6

7

8

9

10

import { lazy, suspense } from 'react';

const lazycomponent = lazy(() =&gt; import('./lazycomponent'));

const app = () =&gt; {

  return (

    <suspense fallback="{&lt;div">loading...}&gt;

      <lazycomponent></lazycomponent></suspense>

  );

};

20. 用于类型检查的 proptypes

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

1

2

3

4

5

6

7

8

9

import PropTypes from 'prop-types';

const Greeting = ({ name }) =&gt; {

  return <h1>Hello, {name}!</h1>;

};

Greeting.propTypes = {

  name: PropTypes.string.isRequired,

};

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

免责声明
1. 本站所有资源来源于用户上传和网络等,如有侵权请邮件联系本站整改team@lcwl.fun!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系本站工作人员处理!
6. 本站资源售价或VIP只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 因人力时间成本问题,部分源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
9.本站所有源码资源都是经过本站工作人员人工亲测可搭建的,保证每个源码都可以正常搭建,但不保证源码内功能都完全可用,源码属于可复制的产品,无任何理由退款!

网站搭建学习网 web前端 React 备忘单:功能组件版 https://www.xuezuoweb.com/9779.html

常见问题
  • 本站所有的源码都是经过平台人工部署搭建测试过可用的
查看详情
  • 购买源码资源时购买了带主机的套餐是指可以享受源码和所选套餐型号的主机两个产品,在本站套餐里开通主机可享优惠,最高免费使用主机
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

Fa快捷助手
手机编程软件开发

在手机上用手点一点就能轻松做软件

去做软件
链未云主机
免备案香港云主机

开通主机就送域名的免备案香港云主机

去使用
链未云服务器
免备案香港云服务器

支持售后、超低价、稳定的免备案香港云服务器

去使用