首先在构造函数中写入数据
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>
)
}