用es6模板字符串的方式绑定了一个.border样式和一个动态样式.active
<View
className={`border ${index === this.state.currentIndex ? "active" : null}`}
>
</View>
用数组的形式
<View
className={['txt', index === this.state.currentIndex ? "txt-active" : null]}
>
{item.title}
</View>
然后在点击的时候调方法,改变状态值,动态样式绑定。
onClick={this.changeNavState.bind(this, index)}
changeNavState(v) {
this.setState(() => {
return {
currentIndex: v
};
});
}
完整代码
import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import './repairmanList.scss'
export default class repairmanList extends Component {
config = {
navigationBarTitleText: '师傅列表'
}
constructor() {
super(...arguments)
this.state = {
currentIndex: 0,
navList: [{
title: '综合排序',
}, {
title: '距离近',
}, {
title: '销量高',
}, {
title: '速度快',
},],
}
}
changeNavState(v) {
this.setState(() => {
return {
currentIndex: v
};
});
}
render() {
let { navList, businessInfoItem } = this.state
return (
<View className='repairmanList-container'>
<View className='nav-title'>
{
navList.map((item, index) => (
<View className='item'
onClick={this.changeNavState.bind(this, index)}
key={item}
>
<View className={['txt', index === this.state.currentIndex ? "txt-active" : null]}>{item.title}</View>
<View className={`border ${index === this.state.currentIndex ? "active" : null}`}></View>
</View>
))
}
</View>
</View>
)
}
}