PHP前端开发

React 备忘单:功能组件版

百变鹏仔 3天前 #JavaScript
文章标签 组件

反应备忘单

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

1. 功能组件基础知识

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

const mycomponent = () =&gt; {  return <div>hello, world!</div>;};

2. 使用 jsx

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

const mycomponent = () =&gt; {  return (    <div>      <h1>welcome to react</h1>    </div>  );};

3.道具

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

57188​​1438247

4.默认道具

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

const greeting = ({ name = "guest" }) =&gt; {  return <h1>hello, {name}!</h1>;};

5. 状态与 usestate

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

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 可让您在功能组件中执行副作用。

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元素。

const loginmessage = ({ isloggedin }) =&gt; {  return (    <div>      {isloggedin ? <h1>welcome back!</h1> : <h1>please log in.</h1>}    </div>  );};

8. 列表和键

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

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

9. 事件处理

处理功能组件中的事件。

const button = () =&gt; {  const handleclick = () =&gt; {    alert('button clicked!');  };  return <button onclick="{handleclick}">click me</button>;};

10. 表格和受控组件

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

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 (    
submit );};

11. 上下文api

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

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. 自定义挂钩

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

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

13. 使用 usememo 进行记忆

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

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 来记忆函数,以防止不必要的重新渲染。

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 管理复杂的状态逻辑。

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 添加额外的节点。

const mycomponent = () =&gt; {  return (          <h1>title</h1>      <p>description</p>    &gt;  );};

17. 门户网站

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

import { createportal } from 'react-dom';const modal = ({ children }) =&gt; {  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></mycomponent></errorboundary>

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

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

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 类型。

import PropTypes from 'prop-types';const Greeting = ({ name }) =&gt; {  return <h1>Hello, {name}!</h1>;};Greeting.propTypes = {  name: PropTypes.string.isRequired,};

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