Taro - 最佳实践
# 安装
# 目录
├── babel.config.js # Babel 配置
├── .eslintrc.js # ESLint 配置
├── config # 编译配置目录
│ ├── dev.js # 开发模式配置
│ ├── index.js # 默认配置
│ └── prod.js # 生产模式配置
├── package.json # Node.js manifest
├── dist # 打包目录
├── project.config.json # 小程序项目配置
├── src # 源码目录
│ ├── app.config.js # 全局配置
│ ├── app.css # 全局 CSS
│ ├── app.js # 入口组件
│ ├── index.html # H5 入口 HTML
│ └── pages # 页面组件
│ └── index
│ ├── index.config.js # 页面配置
│ ├── index.css # 页面 CSS
│ └── index.jsx # 页面组件,如果是 Vue 项目,此文件为 index.vue
# 命名规范
- 文件夹:一律用 kebab-case(短横线)
- 组件文件命名:React 组件用 PascalCase
- hooks 命名:必须以
use开头 - 工具函数:用 kebab-case 或 camelCase(推荐 camelCase)
formatDistance.ts
calcCenterPoint.ts
geoUtils.ts
# 入口组件 - src/app.js
- 类似于根目录的 index.html
- 每一个入口组件都有一个全局配置文件(例如
app.config.js)
export default {
pages: ['pages/index/index'],
}
Note
- 无论是 React 还是 Vue,配置文件格式、内容都是完全一样的
- Taro 的入口组件和全局配置规范是基于微信小程序而制定的,并对全平台进行统一。
# 页面组件
import { View } from '@tarojs/components'
class Index extends Component {
state = {
msg: 'Hello World!',
}
onReady() {
console.log('onReady')
}
render() {
return <View>{this.state.msg}</View>
}
}
export default Index
- 默认存在
src/pages目录下 View组件。来源于@tarojs/components的跨平台组件。相对于div、span元素,在 Taro 中我们要全部使用跨平台组件进行开发。- 每一个页面组件(例如
index.vue)也会有一个页面配置(例如index.config.js),可以在页面配置文件中设置页面的导航栏、背景颜色等参数:
export default {
navigationBarTitleText: '首页',
}
# 自定义组件
# 定义
src/components/thread_list.jsx
import React from 'react'
import { View, Text } from '@tarojs/components'
import { Thread } from './thread'
import { Loading } from './loading'
import './thread.css'
class ThreadList extends React.Component {
static defaultProps = {
threads: [],
loading: true,
}
render() {
const { loading, threads } = this.props
if (loading) {
return <Loading />
}
const element = threads.map((thread, index) => {
return (
<Thread
key={thread.id}
node={thread.node}
title={thread.title}
last_modified={thread.last_modified}
replies={thread.replies}
tid={thread.id}
member={thread.member}
/>
)
})
return <View className="thread-list">{element}</View>
}
}
export { ThreadList }
# 引入
上次更新: 2026/07/01, 13:55:06