React学习(基础)
1. React.js 简介
React 是 Facebook 开发的一个用于构建用户界面的 JavaScript 库。它采用组件化的思想,允许开发者通过构建可复用的组件来创建复杂的用户界面。
核心概念:
- 组件化:React 应用由组件构成,组件是 UI 的基本单元。
- 虚拟 DOM:React 通过虚拟 DOM 提高性能,减少直接操作真实 DOM 的次数。
- JSX:JavaScript 的语法扩展,允许在 JavaScript 中编写类似 HTML 的代码。
2. 环境搭建
首先,你需要安装 Node.js 和 npm(Node 包管理器),然后使用 create-react-app
创建一个新的 React 项目。
npx create-react-app my-app
cd my-app
npm start
3. JSX 语法
JSX 是 JavaScript 的一种语法扩展,允许你在 JavaScript 中编写类似 HTML 的代码。
const element = <h1>Hello, world!</h1>;
解释:<h1>Hello, world!</h1>
是 JSX 语法,最终会被编译为 React.createElement('h1', null, 'Hello, world!')
。
4. 组件
React 应用由组件构成。组件可以是函数组件或类组件。
4.1 函数组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
解释:Welcome
是一个函数组件,接收 props
作为参数,返回一个 JSX 元素。
4.2 类组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
解释:Welcome
是一个类组件,继承自 React.Component
,必须实现 render
方法。
5. Props 和 State
Props 是组件的输入参数,由父组件传递给子组件。
State 是组件的内部状态,用于存储组件的数据。
5.1 Props
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
<Welcome name="Alice" />;
解释:name="Alice"
是 Welcome
组件的 props
。
5.2 State
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
解释:Clock
组件使用 state
来存储当前时间,并通过 setInterval
每秒更新一次时间。
6. 事件处理
React 事件采用驼峰命名法,如 onClick
、onChange
等。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
// 绑定 this 到 handleClick 方法
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
解释:handleClick
方法用于切换 isToggleOn
状态,onClick
事件绑定到 handleClick
方法。
7. 列表和 Keys
在 React 中,你可以使用 map()
方法渲染列表。每个列表项需要一个唯一的 key
。
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<li key={number.toString()}>{number}</li>
);
return <ul>{listItems}</ul>;
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(<NumberList numbers={numbers} />, document.getElementById('root'));
解释:key
用于帮助 React 识别哪些项被更改、添加或删除。
8. 表单
React 表单元素通常使用受控组件来处理用户输入。
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
解释:value
属性受 state
控制,onChange
事件处理输入变化。
9. 生命周期方法
React 组件有多个生命周期方法,你可以在组件挂载、更新或卸载时执行代码。
class ExampleComponent extends React.Component {
componentDidMount() {
console.log('Component is mounted');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component is updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Hello, world!</div>;
}
}
解释:componentDidMount
在组件挂载后调用,componentDidUpdate
在组件更新后调用,componentWillUnmount
在组件卸载前调用。
10. Hooks
Hooks 是 React 16.8 引入的新特性,允许你在不编写类组件的情况下使用 state 和其他 React 特性。
10.1 useState
useState
用于在函数组件中使用 state。
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
解释:useState
返回一个数组,第一个元素是 state,第二个元素是更新 state 的函数。
10.2 useEffect
useEffect
用于在函数组件中执行副作用操作。
function Example() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
解释:useEffect
在组件渲染后执行,[count]
表示只在 count
变化时执行。
11. 使用场景
- 单页应用(SPA):React 常用于构建单页应用,通过路由切换不同的页面。
- 复杂用户界面:React 的组件化思想适合构建复杂的用户界面。
- 数据驱动的 UI:React 与状态管理库(如 Redux)结合,适合构建数据驱动的 UI。
12. 第三方库和工具
- React Router:用于在 React 应用中实现路由。
- Redux:用于管理应用的状态。
- Axios:用于发送 HTTP 请求。