查询字符串的形式传参
在Taro中进行传参,一般会使用查询字符串的形式,也就是在跳转的url上,加一个?问号的形式,然后后边跟上参数。
现在我们就在Blog.jsx页面用,useState的形式声明一个变量,再通过跳转把值带到Index.jsx页面。
import Taro ,{useState}from '@tarojs/taro'import {View , Text ,Button} from '@tarojs/components'function Blog(){const [blogTitle,setBlogTitle]=useState('JSPang Blog')const gotoIndex=()=>{Taro.navigateTo({url:'/pages/index/index?blogTitle='+blogTitle})}return (<View><Text>Blog Page</Text><Button onClick={gotoIndex}>我要去Index页面</Button></View>)}export default Blog
接收传递的参数并显示到页面上
现在参数已经可以传递了,那如何在Index.jsx进行接收那,其实也非常简单。只要使用this.$router.params就可以进行接收。
当然我们要接收参数,可以在useEffect()中进行,
useEffect(()=>{setBlogTitle(this.$router.params.blogTitle)},[])
import Taro, { useState ,useEffect} from '@tarojs/taro'import { View, Text } from '@tarojs/components'import Child from './child.jsx'import './index.less'function Index(props){const [userName ,setUserName] = useState('Hello World!!!!')const [blogTitle,setBlogTitle] = useState('')useEffect(()=>{setBlogTitle(this.$router.params.blogTitle)},[])return (<View><Text>{userName}</Text><Child userName={userName}></Child><View>{blogTitle}</View></View>)}export default Index
多参数的传递和接收
我们再来看看如何传递多个参数和多个参数的接收,传递的时候只要用&进行链接就可以了,比如下面这样。
Taro.navigateTo({url:'/pages/index/index?blogTitle='+blogTitle+'&introduce='+introduce})
import Taro ,{useState}from '@tarojs/taro'import {View , Text ,Button} from '@tarojs/components'function Blog(){introduceconst [blogTitle,setBlogTitle]=useState('JSPangBlog')const [introduce,setIntroduce]=useState('111111')const gotoIndex=()=>{Taro.navigateTo({url:'/pages/index/index?blogTitle='+blogTitle+'&introduce='+introduce})}return (<View><Text>Blog Page</Text><Button onClick={gotoIndex}>我要去Index页面</Button></View>)}export default Blog
接收参数跟单参数接收方法一样
import Taro, { useState ,useEffect} from '@tarojs/taro'import { View, Text } from '@tarojs/components'import Child from './child.jsx'import './index.less'function Index(props){const [userName ,setUserName] = useState('Hello World!!!!')const [blogTitle,setBlogTitle] = useState('')const [introduce,setIntroduce]=useState('')useEffect(()=>{setBlogTitle(this.$router.params.blogTitle)setIntroduce(this.$router.params.introduce)},[])return (<View><Text>{userName}</Text><Child userName={userName}></Child><View>{blogTitle}</View><View>{introduce}</View></View>)}export default Index
