React.js 实践教程
React.js 是一个用于构建用户界面的 JavaScript 库,它可以帮助开发者创建动态和响应式的网页应用。本教程将带你了解 React.js 的基本概念和实际应用。
React.js 简介
React.js 由 Facebook 开发,它允许开发者使用声明式的方式来构建 UI。React.js 的核心是组件化思想,通过组件来构建应用,使得代码更加模块化和可复用。
实践项目
以下是一个简单的 React.js 实践项目,我们将创建一个待办事项列表:
- 创建一个新的 React 应用
- 添加状态来存储待办事项
- 添加一个输入框来添加新的待办事项
- 显示待办事项列表
React.js 待办事项列表示例
组件化
在 React.js 中,组件是构建应用的基本单元。组件可以是函数或类,它们都有自己的状态和方法。
函数组件
function TodoItem(props) {
return <li>{props.text}</li>;
}
类组件
class TodoItem extends React.Component {
render() {
return <li>{this.props.text}</li>;
}
}
状态提升
在 React.js 中,状态通常存储在组件中。但是,当多个组件需要访问同一个状态时,就需要使用状态提升。
class App extends React.Component {
state = {
todos: []
};
addTodo = text => {
this.setState(prevState => ({
todos: [...prevState.todos, text]
}));
};
render() {
return (
<div>
<TodoInput onAdd={this.addTodo} />
<TodoList todos={this.state.todos} />
</div>
);
}
}
更多资源
如果你想要了解更多关于 React.js 的知识,可以访问我们的 React.js 教程 页面。
React.js is a JavaScript library for building user interfaces. It allows developers to create dynamic and responsive web applications. This tutorial will guide you through the basics of React.js and its practical applications.
## Introduction to React.js
React.js is developed by Facebook and allows developers to build UIs using a declarative approach. The core idea of React.js is component-based, making the code more modular and reusable.
## Practical Project
Below is a simple practical project using React.js, where we will create a to-do list:
1. Create a new React application
2. Add state to store to-do items
3. Add an input box to add new to-do items
4. Display the to-do list

## Componentization
In React.js, components are the basic building blocks of an application. Components can be functions or classes and have their own state and methods.
### Function Component
```jsx
function TodoItem(props) {
return <li>{props.text}</li>;
}
Class Component
class TodoItem extends React.Component {
render() {
return <li>{this.props.text}</li>;
}
}
State Lift
In React.js, state is typically stored within a component. However, when multiple components need to access the same state, state lift is used.
class App extends React.Component {
state = {
todos: []
};
addTodo = text => {
this.setState(prevState => ({
todos: [...prevState.todos, text]
}));
};
render() {
return (
<div>
<TodoInput onAdd={this.addTodo} />
<TodoList todos={this.state.todos} />
</div>
);
}
}
More Resources
If you want to learn more about React.js, you can visit our React.js Tutorial page.