2024您的最新学习工具React是用于创建用户界面的JavaScript库。它使开发人员能够构建可重复使用的UI组件,并通过使用虚拟DOM进行最佳性能来有效地更新DOM。
如果您想完全使用React创建一个新的应用程序或网站,我建议选择一个在社区中流行的反应供电框架之一。
您可以在没有框架的情况下使用React,但是我们发现大多数应用程序和站点最终都需要解决常见问题,例如代码分配,路由,数据获取和HTML生成。这些挑战并不是反应的独特之处,而是所有UI库的共同点。
通过从框架开始,您可以快速与React启动并运行,并避免以后开发自己的框架。
Next.js的页面路由器是一个全栈React框架。它是通用的,可让您创建任何大小的React应用程序 - 从大多数静态博客到复杂的动态应用程序。要创建一个新的next.js项目,请在您的终端中运行:
npx create-next-app@latest
Next.js由Vercel维护。您可以将next.js应用程序部署到任何node.js或无服务器托管,也可以将其部署到您自己的服务器。 Next.js还支持不需要服务器的静态导出。
o应用程序路由器do next.js是NEXT.JS API的重新设计。它使您可以在服务器上甚至在构建过程中运行的异步组件中获取数据。
Next.js由Vercel维护。您可以将next.js应用程序部署到任何node.js或无服务器托管,也可以将其部署到您自己的服务器。 Next.js还支持不需要服务器的静态导出。
概述VITE(“快速”,发音为 /VIT /(例如“ Veet”)的法语单词是一种构建工具,旨在为现代网络项目提供更快,更精美的开发体验。它由两个主要部分组成:
提供与本机ES模块相比,提供丰富功能增强功能的开发服务器,例如极快的热模块更换(HMR)。
将您的代码与汇总捆绑在一起的构建命令,并预先配置,以输出高度优化的静态资产进行生产。
Vite是自以为是的,并带有明智的默认设置。阅读功能指南中的可能性。通过插件可以支持框架或与其他工具集成。 “配置”部分说明了如何在需要的情况下将Vite适应您的项目。
在开始之前,请确保系统上安装了node.js。如果您还没有它,则可以从官方Node.js网站下载它,这真的很简单。
npx create-vite your-project-name --template react
用项目的名称替换您的项目名称。 Vite支持许多框架,但是在这种情况下,我们使用-template React选项指定了React模板。
cd your-project-name
不要忘记用您为项目选择的实际名称替换您的项目名称(当然,除非要保留项目的名称)。
npm
npm run dev
运行这些命令后,您应该在终端中看到一条消息,表明您的React网站在特定端口上运行,通常是http:// localhost:5173的“随机”端口号。现在,打开浏览器并访问提供的URL,以查看您的React网站正在行动。
使用React开发人员工具来检查React组件,编辑道具和状态,并确定性能问题。
浏览器扩展程序是通过React构建的调试网站的最简单方法是安装React开发人员工具浏览器扩展程序。它可用于几个流行的浏览器:
对于其他浏览器(例如Safari),请安装React-Devtools NPM软件包:
# Yarn
yarn global add react-devtools
# Npm
npm install -g react-devtools
接下来,从终端打开开发人员工具:
react-devtools
然后通过将以下<script>标签添加到网站的开头来连接您的网站:
<html>
<head>
<script src="http://localhost:8097"></script>
JSX是JavaScript的语法扩展,看起来与XML或HTML相似。它允许开发人员在JavaScript文件中以更简洁和可读的方式编写HTML元素和组件。
import React from 'react';
function App() {
return (
<div>
<h1>Hello, React!</h1>
</div>
);
}
export default App;
功能组件是简单的功能,可以接受Prop作为参数并返回JSX元素。使用React钩子,功能组件也可以具有状态和副作用。
import React from 'react';
const FunctionalComponent = () => {
return <p>This is a functional component.</p>;
}
export default FunctionalComponent;
类组件是扩展React组件的ES6类。他们可以维护和管理局部状态,并可以访问生命周期方法,从而使其比功能组件更丰富。
import React, { Component } from 'react';
class ClassComponent extends Component {
render() {
return <p>This is a class component.</p>;
}
}
export default ClassComponent;
道具是将数据从父组件传递到React中子组件的一种方式。它们是不变的,并提供了使组件动态和重复使用的方法。
import React from 'react';
const PropsExample = (props) => {
return <p>{props.message}</p>;
}
export default PropsExample;
状态反应代表组件的变化状态。这允许组件可以管理和更新自己的数据,从而产生动态和交互式用户界面。
import React, { Component } from 'react';
class StateExample extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
export default StateExample;
生命周期方法sãoMétodosespeciais em em部分de classe quesãoinvocados em diferentes of dio ciclo de vida de um componente。 ComponentDidmountéumMétododeciclo de vida comummente Utilizado,executado depois de um componente ser renderizado no dom。
import React, { Component } from 'react';
class LifecycleExample extends Component {
componentDidMount() {
console.log('Component is mounted!');
}
render() {
return <p>Lifecycle Example</p>;
}
}
export default LifecycleExample;
React使用骆驼处理事件。可以定义功能来处理诸如点击,更改等事件,从而为组件提供交互性。
import React from 'react';
const EventHandlingExample = () => {
const handleClick = () => {
alert('Button clicked!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
export default EventHandlingExample;
React钩子是允许功能组件管理状态和副作用的功能。它们是在React 16.8中引入的,并提供了一种更简洁的方式,可以在功能组件中使用状态和生命周期方法。
import React, { useState } from 'react';
const UseStateExample = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default UseStateExample;
React中的受控组件具有输入,其状态由React控制。他们收到当前价值,而Onchange处理程序作为道具,使它们由React而不是DOM控制。
import React, { useState } from 'react';
const ControlledComponent = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
}
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
placeholder="Type here"
/>
);
}
export default ControlledComponent;
错误边界是React组件,可检测儿童组件树中任何地方的JavaScript错误并记录这些错误,呈现后备UI或采取其他操作。
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <p>Something went wrong.</p>;
}
return this.props.children;
}
}
export default ErrorBoundary;
高阶组件(HOC)是采用组件并返回具有其他功能的新组件的功能。它们是重复使用组件逻辑的一种方式。
import React from 'react';
const WithLogger = (WrappedComponent) => {
return class extends React.Component {
componentDidMount() {
console.log('Component is mounted!');
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
export default WithLogger;
// Usage
import React from 'react';
import WithLogger from './WithLogger';
const MyComponent = () => {
return <p>My Component</p>;
}
const EnhancedComponent = WithLogger(MyComponent);
React提供了map功能,以动态渲染项目列表。数组中的每个项目都映射到React元素,从而更容易呈现动态内容。
import React from 'react';
const RenderingList = () => {
const items = ['Item 1', 'Item 2', 'Item 3'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
export default RenderingList;
React中的上下文API提供了一种通过组件树传输数据的方法,而无需在每个级别手动通过道具。这对于共享诸如主题或身份验证状态之类的值很有用。
import React from 'react';
const ThemeContext = React.createContext('light');
export default ThemeContext;
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
const ThemedComponent = () => {
const theme = useContext(ThemeContext);
return <p style={{ color: theme === 'light' ? 'black' : 'white' }}>Themed Component</p>;
}
export default ThemedComponent;
React中的密钥有助于确定已更改,添加或删除的项目。它们应该在列表中是唯一的,并有助于对有效的更新做出反应。
import React from 'react';
const KeysExample = () => {
const data = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
export default KeysExample;
React中的处理表格涉及使用状态和通过事件处理程序处理表单提交的表单数据进行管理。受控组件用于将形式元素与React的状态同步。
import React, { useState } from 'react';
const FormExample = () => {
const [formData, setFormData] = useState({ username: '', password: '' });
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
}
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form submitted:', formData);
}
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</label>
<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default FormExample;
内联样式:React允许您使用内联样式样式的组件进行样式,其中样式被定义为对象并直接应用于元素。
import React from 'react';
const InlineStyleExample = () => {
const styles = {
color: 'blue',
fontSize: '18px',
};
return <p style={styles}>Styled with inline styles</p>;
}
export default InlineStyleExample;
渲染道具是一种使用一个值为函数的Prop之间在React组件之间共享代码的技术。这允许组件的动态组成。
import React, { useState } from 'react';
const MouseTracker = ({ render }) => {
const [position, setPosition] = useState({ x: 0, y: 0 });
const handleMouseMove = (event) => {
setPosition({ x: event.clientX, y: event.clientY });
}
return (
<div style={{ height: '100vh' }} onMouseMove={handleMouseMove}>
{render(position)}
</div>
);
}
export default MouseTracker;
// Usage
import React from 'react';
import MouseTracker from './MouseTracker';
const App = () => {
return (
<MouseTracker
render={(position) => (
<p>
Mouse position: {position.x}, {position.y}
</p>
)}
/>
);
}
export default App;
CSS模块有助于定义特定组件的样式范围,避免全球样式冲突。每个组件可以具有自己的CSS模块,并具有本地范围的样式。
.myComponent {
color: green;
}
import React from 'react';
import styles from './CSSModulesExample.module.css';
const CSSModulesExample = () => {
return <p className={styles.myComponent}>Styled with CSS Modules</p>;
}
export default CSSModulesExample;
特征:
import React, { useState } from 'react';
const TodoApp = () => {
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState('');
const addTask = () => {
setTasks([...tasks, { text: newTask, completed: false }]);
setNewTask('');
};
const toggleTask = (index) => {
const updatedTasks = [...tasks];
updatedTasks[index].completed = !updatedTasks[index].completed;
setTasks(updatedTasks);
};
const removeTask = (index) => {
const updatedTasks = [...tasks];
updatedTasks.splice(index, 1);
setTasks(updatedTasks);
};
return (
<div>
<input
type="text"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((task, index) => (
<li key={index}>
<input
type="checkbox"
checked={task.completed}
onChange={() => toggleTask(index)}
/>
<span style={{ textDecoration: task.completed ? 'line-through' : 'none' }}>
{task.text}
</span>
<button onClick={() => removeTask(index)}>Remove</button>
</li>
))}
</ul>
</div>
);
};
export default TodoApp;
此天气应用示例说明了React概念的实际应用,包括国家管理,副作用,事件处理,API相互作用和有条件渲染的使用效果。用户可以学习如何创建功能性的天气应用程序,并了解React Hooks在现实世界中的集成。
童恋:
功能组件和状态钩:
weather和city useState钩子控制的。使用使用效应获得数据:
useEffect挂钩用于执行副作用,例如从OpenWeatherMap API获取天气数据。
fetchWeatherData功能是异步的,使用fetch API根据所选城市获取天气数据。
条件渲染:
天气数据只有在存在的情况下才会渲染( weather && ... )。
事件处理:
onChange事件中调用setCity函数。API相互作用:
动态更新内容:
造型:
温度转换:
// src/RealWorldExamples/WeatherApp.js
import React, { useState, useEffect } from 'react';
const WeatherApp = () => {
const [weather, setWeather] = useState(null);
const [city, setCity] = useState('New York');
const apiKey = 'YOUR_OPENWEATHERMAP_API_KEY';
useEffect(() => {
// Fetch weather data from OpenWeatherMap API
const fetchWeatherData = async () => {
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
);
if (!response.ok) {
throw new Error('Failed to fetch weather data');
}
const data = await response.json();
setWeather(data);
} catch (error) {
console.error(error.message);
}
};
fetchWeatherData();
}, [city, apiKey]);
return (
<div>
<h1>Weather App</h1>
<label>
Enter City:
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
/>
</label>
{weather && (
<div>
<h2>{weather.name}, {weather.sys.country}</h2>
<p>Temperature: {Math.round(weather.main.temp - 273.15)}°C</p>
<p>Weather: {weather.weather[0].description}</p>
</div>
)}
</div>
);
};
export default WeatherApp;
最佳实践:
/src
/components
/Button
Button.js
Button.test.js
Button.css
/features
/Todo
TodoList.js
TodoItem.js
TodoForm.js
/styles
global.css
/tests
/unit
Button.test.js
/integration
TodoIntegration.test.js
最佳实践:
// Using React.memo
const MemoizedComponent = React.memo(({ data }) => {
// Component logic
});
// Using Code Splitting and Lazy Loading
const MyComponent = React.lazy(() => import('./MyComponent'));
// In your component
const App = () => (
<React.Suspense fallback={<LoadingSpinner />}>
<MyComponent />
</React.Suspense>
);
最佳实践:
例子:
// Jest Unit Test
test('renders correctly', () => {
const { getByText } = render(<Button label="Click me" />);
expect(getByText('Click me')).toBeInTheDocument();
});
// Jest Integration Test
test('increments count on button click', () => {
const { getByText } = render(<Counter />);
fireEvent.click(getByText('Increment'));
expect(getByText('Count: 1')).toBeInTheDocument();
});
// React Testing Library
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('clicking button increments count', () => {
render(<MyComponent />);
userEvent.click(screen.getByRole('button'));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
最佳实践:
在单页应用程序中使用React路由器作为客户端路由。
定义到您应用程序的不同视图或部分的路由。
实现导航组件,例如<Link> ,以便在路线之间轻松导航。
例子:
// React Router
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const App = () => (
<Router>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Router>
);
最佳实践:
// Using Local Component State
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
// Using Context API
const ThemeContext = React.createContext('light');
const ThemedComponent = () => {
const theme = useContext(ThemeContext);
return <p style={{ color: theme === 'light' ? 'black' : 'white' }}>Themed Component</p>;
};
// Using Redux
// (Assuming you have a Redux store configured)
import { useSelector, useDispatch } from 'react-redux';
const CounterRedux = () => {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</div>
);
};
最佳实践:
例子:
最佳实践:
例子:
// Error Boundary
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <p>Something went wrong. Please try again.</p>;
}
return this.props.children;
}
}
最佳实践:
例子:
// Semantic HTML Elements
<article>
<h2>Article Title</h2>
<p>Article content...</p>
</article>
// ARIA Roles and Attributes
<button aria-label="Close" onClick={handleClose}>
✕
</button>
// Keyboard Navigation
<input type="text" onKeyDown={handleKeyDown} />
最佳实践:
例子:
// Using React.memo
const MemoizedComponent = React.memo(({ data }) => {
// Component logic
});
// Using Code Splitting and Lazy Loading
const MyComponent = React.lazy(() => import('./MyComponent'));
// In your component
const App = () => (
<React.Suspense fallback={<LoadingSpinner />}>
<MyComponent />
</React.Suspense>
);
// Using PureComponent
class PureCounter extends React.PureComponent {
render() {
return <p>Count: {this.props.count}</p>;
}
定期更新依赖项,以从新功能,错误修复和安全补丁中受益。
关注项目中使用的库和软件包的语义版本控制。
对重大更新保持谨慎,并在更新之前进行彻底测试。
例子:
# Regularly update dependencies
npm update
# Follow semantic versioning
# Example: Major.Minor.Patch
# ^1.2.3 means any version that is compatible with 1.2.3
配置WebPack以进行优化的生产构建:
// webpack.config.js
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
// Other webpack configurations...
};
感谢您对为这项惊人的React教程做出贡献的兴趣!您的贡献有助于使该资源对各个级别的学生更有价值。无论您是修复错误,改进现有功能还是添加全新的功能,您的努力都会有所作为。
**叉子存储库:单击此存储库右上角的“叉”按钮以创建您的副本。
**克隆存储库:使用git clone https://github.com/DaveSimoes/React-Tutorial-2024.git将存储库克隆到本地计算机上
**创建一个分支:使用描述性名称为您的贡献创建一个新的分支: git checkout -b your-feature 。
**进行更改:在适当的文件中进行更改。随意改善现有示例,添加新示例,正确错别字或改进文档。
**提交更改:通过清晰简洁的消息提交更改: git commit -m "Your message here" 。
**推送更改:将更改发送到分叉存储库: git push origin your-feature 。
创建拉动请求:在原始存储库中打开拉动请求。 ForneçaumTítuloClaro,Descreva SuasAlteraçõesE Engie o lut请求。
遵循一致的编码样式。确保您的代码已充分记录,尤其是在添加新示例或功能的情况下。
感谢您考虑为该React教程做出贡献。非常感谢您致力于改善此资源。让我们一起学习和成长!
如果您发现此React教程很有用,请考虑给它一个明星!您的支持令人难以置信,并帮助他人发现这一资源。感谢您成为我们社区和HAP的一员!
反应官方图书馆