Taro,说它不香那是假的,毕竟下面的那段话对于FN developer来说都会心动的。
使用 Taro,我们可以只书写一套代码,再通过 Taro 的编译工具,将源代码分别编译出可以在不同端(微信/百度/支付宝/字节跳动/QQ/京东小程序、快应用、H5、React-Native 等)运行的代码。 ————来自官方文档
Taro基于React的JSX语法下的一套多端开发方案,但在语法上相对于React有所收敛,因为要编译到不同的端平台,为了兼容的最大化,所以某些ES的高级功能可能用不了。所以的项目初始化步骤和Taro规范在Taro官方文档都写明了,
这里就不赘述了,这里说下我接触这个框架的若干问题。
1. 绑定事件和页面跳转
首先在pages目录下新建一个和index文件夹同样的页面test,然后在app.js的config的pages下配置页面
1 2 3 4
| pages: [ 'pages/index/index', 'pages/test/index' ],
|
编辑test页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import Taro, { Component } from '@tarojs/taro' import { View, Text } from '@tarojs/components' import './index.scss'
export default class Index extends Component {
config = { navigationBarTitleText: '测试页' }
render () { return ( <View className='index'> <Text>Hello test!</Text> </View> ) } }
|
然后在index/index.jsx里面导入按钮组件,添加点击事件和方法,在点击事件中使用Taro自带的路由跳转工具
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import Taro, { Component } from '@tarojs/taro' import { View, Text, Button } from '@tarojs/components' import './index.scss'
export default class Index extends Component { config = { navigationBarTitleText: '首页' } handleClick = (e) => { Taro.navigateTo({ url: '/pages/test/index' }) } render () { return ( <View className='index'> <Text>Hello world!</Text> <Button size='mini' onClick={this.handleClick}>点击跳转</Button> </View> ) } }
|
2. 引入自定义组件
首先在src目录下新建components文件夹用于存放所有的自定义组件,新建welcome.jsx,在文件中导入相关组件和类型校验工具
1 2 3 4 5 6 7 8 9 10 11 12 13
| import Taro, { Component } from '@tarojs/taro' import { View, Text } from '@tarojs/components' import PropTypes from 'prop-types'
export default class Welcome extends Component { render () { return <View><Text>Hello, {this.props.name}</Text></View> } }
Welcome.propTypes = { name: PropTypes.string }
|
然后在需要使用的页面直接导入使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import Taro, { Component } from '@tarojs/taro' import { View, Text } from '@tarojs/components' import './index.scss' import Wecome from '../../components/wecome'
export default class Index extends Component {
config = { navigationBarTitleText: '测试页' }
render () { return ( <View className='index'> <Text>Hello test!</Text> <Wecome name='fed' /> </View> ) } }
|
如果,组件使用的是小程序的原生组件,就需要在页面中使用usingComponents配置组件
1 2 3 4 5 6 7
| export default class Index extends Component { config = { usingComponents: { 'bar': '../wxComponent/bar' } } }
|