作为一名 Vue 开发者,第一次接触 React 时可能会感到困惑。虽然两者都是优秀的前端框架,但在开发思维和实现方式上存在较大差异。本文将通过实战示例,帮助你快速掌握 React 开发的核心概念和基本用法。

开发环境搭建

首先,我们需要搭建 React 开发环境。React 官方提供了脚手架工具 Create React App:

# 创建项目
npx create-react-app my-react-app

# 进入项目目录
cd my-react-app

# 启动开发服务器
npm start
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

如果你习惯使用 Vite,也可以使用 Vite 创建 React 项目:

# 使用 Vite 创建项目
npm create vite@latest my-react-app -- --template react

# 进入项目目录
cd my-react-app

# 安装依赖
npm install

# 启动开发服务器
npm run dev
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

基本语法对比

1. 组件定义

Vue 组件(SFC):

<!-- HelloWorld.vue -->
<template>
  <div class="hello">
    {
       { message }}
    <button @click="handleClick">点击</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  methods: {
    handleClick() {
      this.message = 'Clicked!'
    }
  }
}
</script>

<style scoped>
.hello {
  color: blue;
}
</style>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

React 组件:

// HelloWorld.jsx
import React, {
         useState } from 'react';
import './HelloWorld.css';

function HelloWorld() {
        
  const [message, setMessage] = useState('Hello React!');
  
  const handleClick = () => {
        
    setMessage('Clicked!');
  };
  
  return (
    <div className="hello">
      {
        message}
      <button onClick={
          handleClick}>点击</button>
    </div>
  );
}

export default HelloWorld;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

主要区别:

  1. React 使用 JSX 而不是模板语法
  2. React 使用 useState 管理状态,而不是 data 选项
  3. React 的事件处理器直接定义为函数
  4. React 的样式需要单独引入

2. 数据绑定

Vue 的双向绑定:

<template>
  <input v-model="text" />
  <p>{
       { text }}</p>
</template>

<script>
export default {
  data() {
    return {
      text: ''
    }
  }
}
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

React 的受控组件:

function InputComponent() {
        
  const [text, setText] = useState('');
  
  return (
    <>
      <input 
        value={
          text} 
        onChange={
          (e) => setText(e.target.value)} 
      />
      <p>{
        text}</p>
    </>
  );
}