Taro列表渲染及页面路由传参

首先在构造函数中写入数据

constructor(props) {
    super(props)
    this.state = {
      arr: [{
        name: 'zzq',
        age: 18
      },
      {
        name: 'asd',
        age: 12
      },
      {
        name: 'cxvbx',
        age: 22
      }]
    }
  }

页面渲染

 render() {
    const { arr } = this.state
    return (
      <View>{
        arr.map((item, index) => {
          return <View key={index}>{index}---{item.name}--{item.age}</View>
        })
      }
        <Button onClick={this.addPerson}>添加人</Button>
        <Button onClick={this.subtractPerson}>减人</Button>
      </View>
    )
  }

向数组中加减数据

// 加人
  addPerson = () => {
    const { arr } = this.state
    arr.push({
      name: 'NPC' + arr.length,
      age: 20 + arr.length
    })
    this.setState({
      arr
    })
  }
  // 减人
  subtractPerson = () => {
    const { arr } = this.state
    arr.splice(arr.length - 1, 1)
    this.setState({
      arr
    })
  }

效果图:
在这里插入图片描述
现在加个需求:点击对应列表进入另一个页面显示对应的内容
先给每一行加个点击事件 onClick={this.gotoList.bind(this, index)},

 render() {
    const { arr } = this.state
    return (
      <View>{
        arr.map((item, index) => {
          return <View onClick={this.gotoList.bind(this, index)}>{index}---{item.name}--{item.age}</View>
        })
      }
        <Button onClick={this.addPerson}>添加人</Button>
        <Button onClick={this.subtractPerson}>减人</Button>
      </View>
    )
  }

添加对应方法,把每一行的下标当参数传过去,不用箭头函数是因为这样好在onClick事件中传参,而且通过this.gotoList.bind(this)也能改变this的指向

// 去列表页面
  gotoList(index) {
    Taro.navigateTo({ url: `/pages/list/index?index=${index}` })
  }

这样 点击不同的行去list页面能把每一行的index传过去了。
再在list页面就能拿到并显示对应的index了,如果想根据index的不同显示对应不同的页面内容,只需要条件判断来渲染对应的jsx就行了。

import { getCurrentInstance } from '@tarojs/taro'

 render() {
    // 拿到我的页面路由传过来的参数
    const idx = getCurrentInstance().router?.params.index
    return (
      <View className='list'>
        <Text>列表页</Text>
        {idx}
      </View>
    )
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值