taro路由配置和跳轉 路由傳參
頂級組件App pages屬性配置
誰在pages數組最上面,就默認打開誰
import Taro, { Component, Config } from '@tarojs/taro'
import Index from './pages/index'
import './app.less'
// 如果需要在 h5 環境中開啟 React Devtools
// 取消以下注釋:
// if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5') {
// require('nerv-devtools')
// }
class App extends Component {
/**
* 指定config的類型聲明為: Taro.Config
*
* 由於 typescript 對於 object 類型推導只能推出 Key 的基本類型
* 對於像 navigationBarTextStyle: 'black' 這樣的推導出的類型是 string
* 提示和聲明 navigationBarTextStyle: 'black' | 'white' 類型沖突, 需要顯示聲明類型
*/
config: Config = {
pages: [
'pages/island/index',
'pages/index/index'
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
}
}
// 在 App 類中的 render() 函數沒有實際作用
// 請勿修改此函數
render () {
return (
<Index />
)
}
}
Taro.render(<App />, document.getElementById('app'))
路由跳轉
- navigatorTo 三端都支持 小程序、h5、rn 最基本的跳轉
- redirectorTo 沒有上一頁的歷史記錄,其他的和navigatorTo一樣
- switchTab
- navigatorBack 可以返回上一頁
- relaunch 關閉所有頁面,三端都支持
傳遞參數
import Taro, { useState } from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
export default function Index(props) {
const [msg,] = useState('island msg')
const toIndex = () => {
const url = '/pages/index/index?msg=' + msg
Taro.navigateTo({url}) // 可以返回上一頁
// Taro.redirectTo({ url }) // 沒有上一頁的歷史記錄,不能返回
}
return <View>
<Text>island page</Text>
<Button onClick={toIndex}>去index頁面</Button>
</View>
}