Skip to content

React 基础入门

什么是 React

React 是由 Facebook 开发的一个用于构建用户界面的 JavaScript 库。它采用组件化的开发模式,让开发者可以构建可复用的 UI 组件。

React 的特点

  • 组件化:将 UI 拆分为独立的、可复用的组件
  • 虚拟 DOM:提高渲染性能
  • 单向数据流:数据流向清晰,易于调试
  • JSX 语法:在 JavaScript 中写 HTML
  • 生态系统丰富:有大量的第三方库和工具

第一个 React 组件

jsx
import React from 'react';

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

export default Welcome;

JSX 语法

JSX 是 JavaScript 的语法扩展,让你可以在 JavaScript 中写类似 HTML 的代码:

jsx
const element = <h1>Hello, world!</h1>;

// 在 JSX 中使用表达式
const name = 'React';
const element = <h1>Hello, {name}!</h1>;

// JSX 中的条件渲染
const isLoggedIn = true;
const element = (
  <div>
    {isLoggedIn ? <h1>欢迎回来!</h1> : <h1>请先登录</h1>}
  </div>
);

组件和 Props

函数组件

jsx
function UserCard(props) {
  return (
    <div className="user-card">
      <h2>{props.name}</h2>
      <p>年龄: {props.age}</p>
      <p>邮箱: {props.email}</p>
    </div>
  );
}

// 使用组件
<UserCard name="张三" age={25} email="zhangsan@example.com" />

类组件

jsx
class UserCard extends React.Component {
  render() {
    return (
      <div className="user-card">
        <h2>{this.props.name}</h2>
        <p>年龄: {this.props.age}</p>
        <p>邮箱: {this.props.email}</p>
      </div>
    );
  }
}

State 状态管理

函数组件中使用 State(Hooks)

jsx
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>当前计数: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        增加
      </button>
      <button onClick={() => setCount(count - 1)}>
        减少
      </button>
    </div>
  );
}

类组件中使用 State

jsx
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  }

  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  }

  render() {
    return (
      <div>
        <p>当前计数: {this.state.count}</p>
        <button onClick={this.increment}>增加</button>
        <button onClick={this.decrement}>减少</button>
      </div>
    );
  }
}

事件处理

jsx
function Button() {
  const handleClick = (event) => {
    event.preventDefault();
    console.log('按钮被点击了!');
  };

  return (
    <button onClick={handleClick}>
      点击我
    </button>
  );
}

列表渲染

jsx
function TodoList() {
  const todos = [
    { id: 1, text: '学习 React', completed: false },
    { id: 2, text: '写代码', completed: true },
    { id: 3, text: '休息', completed: false }
  ];

  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          {todo.text} - {todo.completed ? '已完成' : '未完成'}
        </li>
      ))}
    </ul>
  );
}

生命周期(类组件)

jsx
class LifecycleDemo extends React.Component {
  constructor(props) {
    super(props);
    console.log('1. constructor');
  }

  componentDidMount() {
    console.log('3. componentDidMount');
  }

  componentDidUpdate() {
    console.log('4. componentDidUpdate');
  }

  componentWillUnmount() {
    console.log('5. componentWillUnmount');
  }

  render() {
    console.log('2. render');
    return <div>生命周期演示</div>;
  }
}

总结

React 是一个强大的 UI 库,通过组件化的开发模式让前端开发更加高效。掌握 React 的基础概念是学习现代前端开发的重要一步。