当前位置:   article > 正文

Taro 小程序开发大型实战(二):多页面跳转和 Taro UI 组件库

taro 页面跳转顶部进度条实现

上一篇教程中,我们用熟悉的 React 和 Hooks 搞定了“奥特曼俱乐部”的雏形。在这一篇文章中,我们将用 Taro 自带的路由功能实现多页面跳转,并用 Taro UI 组件库升级之前略显简陋的界面。这一篇完成后的 DEMO 如下:

具体有三个页面:

  • 主页:展示了所有帖子,以及添加新帖子的按钮。
  • 帖子详情:展示单个帖子的全部内容。
  • 个人主页:展示当前用户的个人信息。

如果你想直接从这一篇开始动手实践,那么请运行以下命令快速开始:

  1. git clone -b second-part https://github.com/tuture-dev/ultra-club.git
  2. cd ultra-club

本文所涉及的源代码都放在了Github 上,如果您觉得我们写得还不错,希望您能给️这篇文章点赞+Github仓库加星️哦~

来一打页面

在这一步中,我们将开始实现项目的其他页面,包括:

  • 帖子详情 post:进入单篇帖子的详情页面
  • 我的 mine:显示当前用户的个人信息(在后面的步骤中将实现登录注册哦)

其中,帖子详情页面中将复用前面编写的 PostCard 组件。为了方便管理,我们需要引入一个新的 prop(isList),用于判断此组件是显示在首页列表中,还是在帖子详情页面中。

提示

项目中所需用到的图片可以从这个链接下载,下载后解压并将所有图片放到 src/images 目录下。

Taro 的路由功能

路由功能是实现多页面应用的核心,幸运的是 Taro 已经自带了。具体而言,在 Taro 中实现页面跳转只需两个步骤:

  1. 在入口文件(src/app.jsx)中在 App 组件的 config 中配置之前提到的 pages 属性
  2. 在任意组件中通过 Taro.navigateToTaro.redirectTo 即可实现页面的跳转或重定向

感觉不够直观?OK,我们直接撸起袖子写起来。

配置全部页面

首先在入口文件 src/app.jsx 中配置好所有页面:

  1. import Taro, { Component } from '@tarojs/taro'
  2. import Index from './pages/index'
  3. import './app.scss'
  4. // 如果需要在 h5 环境中开启 React Devtools
  5. // 取消以下注释:
  6. // if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5') {
  7. // require('nerv-devtools')
  8. // }
  9. class App extends Component {
  10. config = {
  11. pages: ['pages/index/index', 'pages/mine/mine', 'pages/post/post'],
  12. window: {
  13. backgroundTextStyle: 'light',
  14. navigationBarBackgroundColor: '#fff',
  15. navigationBarTitleText: 'WeChat',
  16. navigationBarTextStyle: 'black',
  17. },
  18. tabBar: {
  19. list: [
  20. {
  21. pagePath: 'pages/index/index',
  22. text: '首页',
  23. iconPath: './images/home.png',
  24. selectedIconPath: './images/homeSelected.png',
  25. },
  26. {
  27. pagePath: 'pages/mine/mine',
  28. text: '我的',
  29. iconPath: './images/mine.png',
  30. selectedIconPath: './images/mineSelected.png',
  31. },
  32. ],
  33. },
  34. }
  35. // 在 App 类中的 render() 函数没有实际作用
  36. // 请勿修改此函数
  37. render() {
  38. return <Index />
  39. }
  40. }
  41. Taro.render(<App />, document.getElementById('app'))

注意到我们还在 config 中注册了导航栏 tabBar,用来在底部切换 index 页面和 mine 页面。

在 PostCard 中添加跳转逻辑

我们首先在 PostCard 组件中添加跳转逻辑,使得它被点击后将进入该帖子的详情页面。将 src/components/PostCard/index.jsx 按如下代码进行修改:

  1. import Taro from '@tarojs/taro'
  2. import { View } from '@tarojs/components'
  3. import './index.scss'
  4. export default function PostCard(props) {
  5. const handleClick = () => {
  6. // 如果是列表,那么就响应点击事件,跳转到帖子详情
  7. if (props.isList) {
  8. const { title, content } = this.props
  9. Taro.navigateTo({
  10. url: `/pages/post/post?title=${title}&content=${content}`,
  11. })
  12. }
  13. }
  14. return (
  15. <View className="postcard" onClick={handleClick}>
  16. <View className="post-title">{props.title}</View>
  17. <View className="post-content">{props.content}</View>
  18. </View>
  19. )
  20. }

可以看到,我们在 PostCard 中注册了 handleClick 用于响应点击事件。在 handleClick 函数中,我们通过新引入的 isList 属性判断这个组件是否展示在首页列表中。如果是的话,就通过 Taro.navigateTo 进行跳转。

提示

眼尖的你一定发现了我们在调用 navigateTo 时还加上了查询字符串用于传递参数。在接下来实现帖子详情页面时,我们就可以接收到传递进来的 titlecontent 的值啦。

接着我们需要在首页模块中给 PostCard 组件加上 isList。修改 src/pages/index/index.jsx,代码如下:

  1. // import 语句 ...
  2. export default function Index() {
  3. // 定义状态和 handleSubmit 函数 ...
  4. return (
  5. <View className="index">
  6. {posts.map((post, index) => (
  7. <PostCard
  8. key={index}
  9. title={post.title}
  10. content={post.content}
  11. isList
  12. />
  13. ))}
  14. <PostForm
  15. formTitle={formTitle}
  16. formContent={formContent}
  17. handleSubmit={e => handleSubmit(e)}
  18. handleTitleInput={e => setFormTitle(e.target.value)}
  19. handleContentInput={e => setFormContent(e.target.value)}
  20. />
  21. </View>
  22. )
  23. }
  24. // ...

实现“帖子详情”页面

src/pages 中创建 post 目录,然后在其中创建 post.jsx 和 post.scss,分别为页面模块和样式文件。post.jsx 代码如下:

  1. import Taro, { useRouter } from '@tarojs/taro'
  2. import { View } from '@tarojs/components'
  3. import { PostCard } from '../../components'
  4. import './post.scss'
  5. export default function Post() {
  6. const router = useRouter()
  7. const { params } = router
  8. return (
  9. <View className="post">
  10. <PostCard title={params.title} content={params.content} />
  11. </View>
  12. )
  13. }
  14. Post.config = {
  15. navigationBarTitleText: '帖子详情',
  16. }

注意到我们用了 useRouter 这个 Hook(Taro 专有),它用来在函数组件中获取 router,等同于之前类组件中的 this.$router。有了 router,我们就可以获取到在刚才 PostCard 组件跳转时传进来的 titlecontent 参数了。

post.scss 的代码如下:

  1. .mine {
  2. margin: 30px;
  3. border: 1px solid #ddd;
  4. text-align: center;
  5. height: 90vh;
  6. padding-top: 40px;
  7. display: flex;
  8. flex-direction: column;
  9. align-items: center;
  10. justify-content: space-between;
  11. }
  12. .mine-avatar {
  13. width: 200px;
  14. height: 200px;
  15. border-radius: 50%;
  16. }
  17. .mine-nickName {
  18. font-size: 40;
  19. margin-top: 20px;
  20. }
  21. .mine-username {
  22. font-size: 32px;
  23. margin-top: 16px;
  24. color: #777;
  25. }
  26. .mine-footer {
  27. font-size: 28px;
  28. color: #777;
  29. margin-bottom: 20px;
  30. }

实现“我的”页面

接着我们实现“我的”页面。创建 src/pages/mine 目录,在其中创建 mine.jsx 和 mine.scss。页面组件 mine.jsx 代码如下:

  1. import Taro from '@tarojs/taro'
  2. import { View, Image } from '@tarojs/components'
  3. import './mine.scss'
  4. import avatar from '../../images/avatar.png'
  5. export default function Mine() {
  6. return (
  7. <View className="mine">
  8. <View>
  9. <Image src={avatar} className="mine-avatar" />
  10. <View className="mine-nickName">图雀酱</View>
  11. <View className="mine-username">tuture</View>
  12. </View>
  13. <View className="mine-footer">From 图雀社区 with Love </View>
  14. </View>
  15. )
  16. }
  17. Mine.config = {
  18. navigationBarTitleText: '我的',
  19. }

样式文件 mine.scss 代码如下:

  1. .mine {
  2. margin: 30px;
  3. border: 1px solid #ddd;
  4. text-align: center;
  5. height: 90vh;
  6. padding-top: 40px;
  7. display: flex;
  8. flex-direction: column;
  9. align-items: center;
  10. justify-content: space-between;
  11. }
  12. .mine-avatar {
  13. width: 200px;
  14. height: 200px;
  15. border-radius: 50%;
  16. }
  17. .mine-nickName {
  18. font-size: 40;
  19. margin-top: 20px;
  20. }
  21. .mine-username {
  22. font-size: 32px;
  23. margin-top: 16px;
  24. color: #777;
  25. }
  26. .mine-footer {
  27. font-size: 28px;
  28. color: #777;
  29. margin-bottom: 20px;
  30. }

查看效果

又到了激动人心的验收环节。我们应该能看到下面所示的效果:

加速开发,Taro UI 帮帮忙

在编写用户界面时,如果每次都要自己编写组件逻辑、调整组件样式,对于学习来说是完全可以的,但是对于实际开发任务就显得很麻烦了。在 React 社区,我们有诸如 Ant Design 这样的组件库,能够让我们快速搭建一套专业美观的界面。而 Taro 也提供了 Taro UI 组件库,为我们提供了能够适应多端的成熟组件。在这一步中,我们将用 Taro UI 升级界面,让它看上去更像一个成熟的小程序。

我们先贴出升级后的 demo 展示:

可以看到我们做了三点改进:

配置 Taro UI

首先安装 Taro UI 的 npm 包:

npm install taro-ui

为了后续能在 H5 中使用 taro-ui,我们需要在 config/index.js 中添加如下配置:

  1. h5: {
  2. esnextModules: ['taro-ui']
  3. }

升级 PostForm

首先让我们升级 PostForm 组件。我们先尝鲜 Taro UI 的 AtButton 组件,替换掉之前 Taro 自带的 Taro 组件:

  1. import Taro from '@tarojs/taro'
  2. import { View, Form, Input, Textarea, Button } from '@tarojs/components'
  3. import { AtButton } from 'taro-ui'
  4. import './index.scss'
  5. export default function PostForm(props) {
  6. return (
  7. <View className="post-form">
  8. <Form onSubmit={props.handleSubmit}>
  9. <View>
  10. <View className="form-hint">标题</View>
  11. <Input
  12. className="input-title"
  13. type="text"
  14. placeholder="点击输入标题"
  15. value={props.formTitle}
  16. onInput={props.handleTitleInput}
  17. />
  18. <View className="form-hint">正文</View>
  19. <Textarea
  20. placeholder="点击输入正文"
  21. className="input-content"
  22. value={props.formContent}
  23. onInput={props.handleContentInput}
  24. />
  25. <AtButton formType="submit" type="primary">
  26. 提交
  27. </AtButton>
  28. </View>
  29. </Form>
  30. </View>
  31. )
  32. }

注意到我们还把之前 <View>添加新的帖子</View> 去掉了,因为接下来我们会把表单放在浮动弹层 FloatLayout 里面,所以就不需要这行提示啦。

提示

你也许会好奇为啥 Taro UI 的组件都以 At 开头?一个是为了与普通的 Taro 组件区分,另一个则是因为开发 Taro 团队正是 Aotu.io 凹凸实验室

调整 PostForm 组件的样式,代码如下:

  1. .post-form {
  2. margin: 0 30px;
  3. padding: 30px;
  4. }
  5. .input-title {
  6. border: 1px solid #eee;
  7. padding: 10px;
  8. font-size: medium;
  9. width: 100%;
  10. }
  11. .input-content {
  12. border: 1px solid #eee;
  13. padding: 10px;
  14. width: 100%;
  15. height: 200px;
  16. font-size: medium;
  17. margin-bottom: 40px;
  18. }
  19. .form-hint {
  20. font-size: small;
  21. color: gray;
  22. margin-top: 20px;
  23. margin-bottom: 10px;
  24. }

正如之前所说,我们打算把创建新帖子的表单放在浮动弹层 FloatLayout 中。在首页模块 src/pages/index/index.jsx 中导入相关组件,代码如下:

  1. import Taro, { useState } from '@tarojs/taro'
  2. import { View } from '@tarojs/components'
  3. import { AtFab, AtFloatLayout, AtMessage } from 'taro-ui'
  4. import { PostCard, PostForm } from '../../components'
  5. import './index.scss'
  6. export default function Index() {
  7. const [posts, setPosts] = useState([
  8. {
  9. title: '泰罗奥特曼',
  10. content: '泰罗是奥特之父和奥特之母唯一的亲生儿子。',
  11. },
  12. ])
  13. const [formTitle, setFormTitle] = useState('')
  14. const [formContent, setFormContent] = useState('')
  15. const [isOpened, setIsOpened] = useState(false)
  16. function handleSubmit(e) {
  17. e.preventDefault()
  18. const newPosts = posts.concat({ title: formTitle, content: formContent })
  19. setPosts(newPosts)
  20. setFormTitle('')
  21. setFormContent('')
  22. setIsOpened(false)
  23. Taro.atMessage({
  24. message: '发表文章成功',
  25. type: 'success',
  26. })
  27. }
  28. return (
  29. <View className="index">
  30. <AtMessage />
  31. {posts.map((post, index) => (
  32. <PostCard
  33. key={index}
  34. title={post.title}
  35. content={post.content}
  36. isList
  37. />
  38. ))}
  39. <AtFloatLayout
  40. isOpened={isOpened}
  41. title="发表新文章"
  42. onClose={() => setIsOpened(false)}
  43. >
  44. <PostForm
  45. formTitle={formTitle}
  46. formContent={formContent}
  47. handleSubmit={e => handleSubmit(e)}
  48. handleTitleInput={e => setFormTitle(e.target.value)}
  49. handleContentInput={e => setFormContent(e.target.value)}
  50. />
  51. </AtFloatLayout>
  52. <View className="post-button">
  53. <AtFab onClick={() => setIsOpened(true)}>
  54. <Text className="at-fab__icon at-icon at-icon-edit"></Text>
  55. </AtFab>
  56. </View>
  57. </View>
  58. )
  59. }
  60. Index.config = {
  61. navigationBarTitleText: '首页',
  62. }

我们来逐一分析新添加的代码:

  • 首先从 taro-ui 导入所需的 AtFabAtFloatLayoutAtMessage 组件
  • 使用 useState Hook 创建新的状态 isOpened(用于记录浮动弹层是否打开)和用于修改状态的 setIsOpened
  • handleSubmit 中,用 setIsOpened(false) 关闭浮动弹层,并用 Taro.atMessage 弹出提示消息
  • return JSX 代码时,添加 <AtMessage /> 组件,并在之前的 PostForm 组件外层包裹 AtFloatLayout 组件,最后添加浮动按钮 AtFab

在首页样式文件 src/pages/index/index.scss 中添加样式如下:

  1. .post-button {
  2. position: fixed;
  3. right: 60px;
  4. bottom: 80px;
  5. }

升级 PostCard

接着我们来调整 PostCard 在不同页面的样式。classnames 是最常用的 CSS 类组合库,可以让你用 JavaScript 表达式灵活地进行 CSS 类的组合。例如我们有三个 CSS 类 foobarfoo-bar,可以通过 classNames 函数进行条件式组合:

  1. import classNames from 'classnames`;
  2. classNames('foo', 'bar'); // => 'foo bar'
  3. classNames('foo', { bar: true }); // => 'foo bar'
  4. classNames({ 'foo-bar': true }); // => 'foo-bar'
  5. classNames({ 'foo-bar': false }); // => ''
  6. classNames({ foo: true }, { bar: true }); // => 'foo bar'
  7. classNames({ foo: true, bar: true }); // => 'foo bar'

我们也新增加一个 CSS 类 postcard__isList,用于表示在帖子列表中的样式。修改 src/components/PostCard/index.jsx 代码如下:

  1. import Taro from '@tarojs/taro'
  2. import { View } from '@tarojs/components'
  3. import classNames from 'classnames'
  4. import './index.scss'
  5. export default function PostCard(props) {
  6. const handleClick = () => {
  7. // ...
  8. }
  9. return (
  10. <View
  11. className={classNames('postcard', { postcard__isList: props.isList })}
  12. onClick={handleClick}
  13. >
  14. <View className="post-title">{props.title}</View>
  15. <View className="post-content">{props.content}</View>
  16. </View>
  17. )
  18. }
  19. PostCard.defaultProps = {
  20. isList: '',
  21. }

修改 PostCard 组件的样式,代码如下:

  1. .postcard {
  2. margin: 30px;
  3. padding: 20px;
  4. }
  5. .postcard__isList {
  6. border: 1px solid #ddd;
  7. }
  8. .post-title {
  9. font-weight: bolder;
  10. margin-bottom: 10px;
  11. }
  12. .post-content {
  13. font-size: medium;
  14. color: #666;
  15. }

定制主题颜色

Taro UI 支持一定程度的主题定制,这里我们采用最简单却也十分有效的 SCSS 变量覆盖。我们创建 src/custom-theme.scss,代码如下:

  1. /* Custom Theme */
  2. $color-brand: #02b875;
  3. $color-brand-light: #41ca98;
  4. $color-brand-dark: #02935e;

可以看到,我们定义了三个 SCSS 变量 $color-brand$color-brand-light$color-brand-dark,覆盖了 Taro UI 的默认主题色。

提示

欲查看所有可以覆盖的 SCSS 变量,请参考 Taro UI 的默认样式文件。如果不熟悉 SCSS 变量,这份指南是不错的资料。

紧接着我们需要在项目的全局样式文件 src/app.scss 中导入自定义颜色主题文件,代码如下:

  1. @import './custom-theme.scss';
  2. @import '~taro-ui/dist/style/components/button.scss';
  3. @import '~taro-ui/dist/style/components/fab.scss';
  4. @import '~taro-ui/dist/style/components/icon.scss';
  5. @import '~taro-ui/dist/style/components/float-layout.scss';
  6. @import '~taro-ui/dist/style/components/textarea.scss';
  7. @import '~taro-ui/dist/style/components/message.scss';
  8. @import '~taro-ui/dist/style/components/avatar.scss';

可以看到,除了导入了刚刚创建的 custom-theme.scss,我们还按需引入了 Taro UI 中所用到组件的样式,这样可以有效减少打包后应用体积的大小哦。

完成这一步的代码后,记得在模拟器里面看看运行起来是不是跟开头的 GIF demo 效果完全一致哦!

至此,《Taro 多端小程序开发大型实战》第二篇也就结束啦。欢迎继续阅读第三篇,我们将手把手带大家用实现如何在 Taro 框架下实现多端登录(微信小程序 + 支付宝小程序 + 普通登录)。

想要学习更多精彩的实战技术教程?来图雀社区逛逛吧。

本文所涉及的源代码都放在了 Github 上,如果您觉得我们写得还不错,希望您能给️这篇文章点赞+Github仓库加星️哦~

作者:一只图雀

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/320883?site=
推荐阅读
相关标签
  

闽ICP备14008679号