AI 工具 | | 约 18 分钟 | 6,817 字

用 Trae 从零构建 React 项目:完整实战

从项目初始化到部署,用 Trae 的 AI 能力完成一个完整的 React 应用开发

项目规划:用 Chat 讨论需求和技术选型

我们要做一个天气仪表盘——搜索城市查天气、5 天预报、温度趋势图、收藏城市。先别急着写代码,打开 Trae Chat 聊聊:

我要做一个天气仪表盘,需要搜索城市、展示天气和预报、温度图表、收藏功能。
帮我分析技术选型和项目结构。

你可以继续追问细节,比如”React Query 和 SWR 哪个更适合”。Chat 就是你的技术顾问,帮你在动手前把方案想清楚。

最终确定的技术选型:

需求选择理由
构建工具Vite快,React 生态首选
类型系统TypeScriptAI 生成代码更准确
样式方案Tailwind CSS原子化 CSS,AI 生成效率高
数据请求React Query缓存、重试、loading 一站式解决
图表RechartsReact 原生,声明式 API
天气 APIOpenWeatherMap免费额度够,文档清晰

配置 Trae Rules:React + TS 规范

在项目根目录创建 .trae/rules,让 AI 生成的代码符合你的规范:

language: TypeScript
framework: React 18
styling: Tailwind CSS

rules:
  - 使用函数组件 + Hooks,不用 class 组件
  - Props 使用 interface 定义,命名为 ComponentNameProps
  - 自定义 Hook 以 use 开头,放在 hooks/ 目录
  - API 请求统一放在 services/ 目录
  - 使用 React Query 管理服务端状态
  - 样式只用 Tailwind,不写自定义 CSS

配好 Rules,后面所有模式生成的代码都会遵循这些规范,省得你反复纠正。


Builder Mode 生成项目骨架

切到 Builder Mode(Cmd + B),输入任务:

用 Vite 创建 React + TypeScript 项目,配置 Tailwind CSS、React Query、
React Router、Recharts。目录结构:components/、pages/、hooks/、services/、types/、utils/

Builder 会自动跑 npm create vite@latest、装依赖、配置 Tailwind、创建目录、生成基础 App.tsx

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Home from './pages/Home'
import Favorites from './pages/Favorites'

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 2 } },
})

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/favorites" element={<Favorites />} />
        </Routes>
      </BrowserRouter>
    </QueryClientProvider>
  )
}
export default App

整个过程 2-3 分钟,你只需要在请求终端权限时点”允许”。


Chat + Inline Edit 开发核心组件

骨架有了,开始写组件。Chat 生成初版,Inline Edit(Cmd + I)微调细节。

在 Chat 里描述搜索组件需求,生成后放到 src/components/SearchBar.tsx

interface SearchBarProps {
  onSearch: (city: string) => void
  isLoading?: boolean
}

export default function SearchBar({ onSearch, isLoading }: SearchBarProps) {
  const [query, setQuery] = useState('')

  const handleSubmit = useCallback(() => {
    if (query.trim()) onSearch(query.trim())
  }, [query, onSearch])

  return (
    <div className="flex gap-2 w-full max-w-md">
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        onKeyDown={(e) => e.key === 'Enter' && handleSubmit()}
        placeholder="输入城市名称..."
        className="flex-1 px-4 py-2 rounded-lg border border-gray-300
                   focus:outline-none focus:ring-2 focus:ring-blue-500"
      />
      <button onClick={handleSubmit} disabled={isLoading}
        className="px-6 py-2 bg-blue-500 text-white rounded-lg
                   hover:bg-blue-600 disabled:opacity-50">
        {isLoading ? '搜索中...' : '搜索'}
      </button>
    </div>
  )
}

天气卡片、预报列表也是同样的流程:Chat 出初版,Inline Edit 调整。


SOLO Mode 实现复杂业务逻辑

收藏城市功能涉及多个文件,交给 SOLO Coder:

实现收藏城市功能:用 localStorage 持久化,创建 useFavorites Hook
提供 add/remove/toggle/isFavorited 方法,创建 Favorites 页面

SOLO Coder 生成的核心 Hook:

export function useFavorites() {
  const [favorites, setFavorites] = useState<string[]>(() => {
    const stored = localStorage.getItem('weather-favorites')
    return stored ? JSON.parse(stored) : []
  })

  useEffect(() => {
    localStorage.setItem('weather-favorites', JSON.stringify(favorites))
  }, [favorites])

  const toggle = useCallback((city: string) => {
    setFavorites(prev =>
      prev.includes(city) ? prev.filter(c => c !== city) : [...prev, city]
    )
  }, [])

  const isFavorited = useCallback(
    (city: string) => favorites.includes(city), [favorites]
  )

  return { favorites, toggle, isFavorited }
}

4 个文件的创建和修改,SOLO 一次性搞定。


样式开发:多模态 + Tailwind CSS

Trae 的多模态能力在样式开发中特别好用。截图一个好看的天气卡片设计,拖到 Chat 里:

参考这张截图的设计风格,用 Tailwind 重写 WeatherCard 样式。
要求渐变背景、毛玻璃效果、圆角卡片。

天气类型和渐变色映射:

天气类型Tailwind 类
晴天bg-gradient-to-br from-amber-400 to-blue-500
多云bg-gradient-to-br from-gray-400 to-slate-600
雨天bg-gradient-to-br from-blue-700 to-slate-500
雪天bg-gradient-to-br from-blue-200 to-white
雷暴bg-gradient-to-br from-purple-900 to-gray-700

比你自己一个个调 CSS 属性快太多了。


API 集成:AI 生成数据获取逻辑

让 Chat 封装 OpenWeatherMap API,用 React Query 包装成 Hook:

// src/services/weatherApi.ts
const API_KEY = import.meta.env.VITE_WEATHER_API_KEY
const BASE = 'https://api.openweathermap.org/data/2.5'

export async function fetchWeather(city: string) {
  const res = await fetch(`${BASE}/weather?q=${city}&appid=${API_KEY}&units=metric&lang=zh_cn`)
  if (!res.ok) throw new Error('城市未找到')
  return res.json()
}

// src/hooks/useWeather.ts
export function useCurrentWeather(city: string) {
  return useQuery({
    queryKey: ['weather', city],
    queryFn: () => fetchWeather(city),
    enabled: !!city,
  })
}

组件里直接用 const { data, isLoading, error } = useCurrentWeather(city) 就行。


测试:AI 生成单元测试

在 Chat 里让 Trae 为 useFavorites 生成 Vitest 测试:

describe('useFavorites', () => {
  beforeEach(() => localStorage.clear())

  it('初始状态为空数组', () => {
    const { result } = renderHook(() => useFavorites())
    expect(result.current.favorites).toEqual([])
  })

  it('toggle 切换收藏状态', () => {
    const { result } = renderHook(() => useFavorites())
    act(() => result.current.toggle('上海'))
    expect(result.current.isFavorited('上海')).toBe(true)
    act(() => result.current.toggle('上海'))
    expect(result.current.isFavorited('上海')).toBe(false)
  })

  it('数据持久化到 localStorage', () => {
    const { result } = renderHook(() => useFavorites())
    act(() => result.current.toggle('广州'))
    expect(JSON.parse(localStorage.getItem('weather-favorites')!)).toEqual(['广州'])
  })
})

AI 写测试效率很高,因为它能直接读到源码,知道要测什么。


构建与部署

在 Builder Mode 里让 Trae 配置生产构建、Vercel 部署和 GitHub Actions CI/CD。它会生成 vercel.json.github/workflows/ci.yml.env.example 等文件。

npm run build      # 本地构建
npm run preview    # 预览构建结果
npx vercel --prod  # 部署到 Vercel

全流程效率回顾

阶段Trae 功能耗时传统耗时
需求分析Chat15 分钟1-2 小时
Rules 配置手动5 分钟
项目骨架Builder3 分钟30 分钟
组件开发Chat + Inline Edit40 分钟3-4 小时
业务逻辑SOLO Coder20 分钟2-3 小时
样式开发多模态 + Chat30 分钟2-3 小时
API 集成Chat15 分钟1-2 小时
单元测试Chat20 分钟2-3 小时
构建部署Builder10 分钟30 分钟
总计约 2.5 小时约 13-18 小时

效率提升大概 5-7 倍。关键不是 AI 替你写了多少代码,而是它帮你跳过了多少”查文档、想方案、写样板代码”的时间。你的精力可以集中在真正需要思考的地方——产品逻辑、用户体验、架构决策。

工具的价值不在于它能做什么,而在于它让你能专注于什么。当 AI 接管了重复劳动,你才有空间去做真正有创造力的事情。

评论

加载中...

相关文章

分享:

评论

加载中...