React 是一个用于构建用户界面的 JavaScript 库,它可以帮助开发者构建高效、可维护的用户界面。以下是一些关于 React 的基础知识。
快速开始
- 安装 Node.js 和 npm:React 需要Node.js 和 npm 来运行。
- 创建一个新的 React 应用:使用
create-react-app
命令来快速搭建项目。 - 编写 React 组件:React 组件是构建 UI 的基础。
组件
React 组件是构成用户界面的最小单元。它们可以是无状态的或是有状态的。
无状态组件
无状态组件是最简单的组件形式,它们不包含任何状态。
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
有状态组件
有状态组件包含状态,可以响应状态的变化来更新 UI。
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
JSX
JSX 是 JavaScript 的语法扩展,它看起来像 HTML,但它是 JavaScript。
const element = <h1>Hello, world!</h1>;
生命周期方法
React 组件在其生命周期中会有多个阶段,每个阶段都有一些方法可以调用。
class LifecycleExample extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
count: this.state.count + 1
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>Count: {this.state.count}</h2>
</div>
);
}
}
资源
想了解更多关于 React 的信息?请访问我们的React 官方文档。