返回
React 入门:开启前端开发之旅
前端
2023-10-20 00:37:32
React 是一个强大的 JavaScript 框架,专为构建用户界面而设计。它采用组件化架构,使开发人员能够轻松地构建和维护复杂的 UI。React 还具有非常高的性能,使其非常适合构建交互性强的应用程序。
在这第一节课中,我们将介绍 React 的基本概念,包括组件、props 和 state。我们还将讨论 React 的生命周期,以及如何使用它来控制组件的行为。
组件
组件是 React 中的基本构建块。它们是独立、可重用的代码块,可以用于创建更复杂的 UI。组件可以是功能组件或类组件。
功能组件
功能组件是使用 JavaScript 函数定义的组件。它们非常简单,只接受 props 作为参数,并返回一个 React 元素。
function MyComponent(props) {
return <div>Hello, {props.name}</div>;
}
类组件
类组件是使用 JavaScript 类定义的组件。它们比功能组件更复杂,但提供了更多的功能。类组件具有状态,可以通过 this.state
对象进行访问。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'John Doe'
};
}
render() {
return <div>Hello, {this.state.name}</div>;
}
}
Props
Props 是组件从父组件接收的数据。它们是只读的,这意味着组件不能修改它们。
<MyComponent name="John Doe" />
State
State 是组件的私有数据。它可以被组件修改,并且会在组件更新时自动更新。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
incrementCount() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
生命周期
组件的生命周期是指组件从创建到销毁的整个过程。React 提供了一系列生命周期方法,用于在组件的不同阶段执行不同的操作。
以下是最常用的生命周期方法:
componentDidMount
:在组件挂载到 DOM 后调用。componentDidUpdate
:在组件更新后调用。componentWillUnmount
:在组件卸载前调用。
结束语
本指南只是 React 入门的开始。要了解更多关于 React 的知识,请查看官方文档。