React 备忘单:功能组件版
来源:dev.to
时间:2024-08-06 22:21:45 382浏览 收藏
大家好,今天本人给大家带来文章《React 备忘单:功能组件版》,文中内容主要涉及到,如果你对文章方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

反应备忘单
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 用于将数据从父组件传递到子组件。
4.默认道具
您可以为组件定义默认 props。
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 备忘单:功能组件版》的详细内容,更多关于的资料请关注golang学习网公众号!
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
278 收藏
-
280 收藏
-
104 收藏
-
120 收藏
-
344 收藏
-
165 收藏
-
369 收藏
-
190 收藏
-
433 收藏
-
163 收藏
-
174 收藏
-
107 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习