城市列表(八)01-右侧字符索引——基本布局 & 高亮索引跟随页面滚动 & 样式-三元表达式 & toUpperCase() 方法将小写字符转换为大写
右侧字符索引
- 右侧索引布局
<li className="city-index-item">
<span className='index-active'>
A
</span>
</li>
- 右侧索引样式
// 右侧索引
.city-index {
position: absolute;
display: flex;
flex-direction: column;
right: 5px;
z-index: 1;
height: 90%;
box-sizing: border-box;
padding-top: 20px;
text-align: center;
.city-index-item {
flex: 1;
}
.index-active {
color: #fff;
background-color: #21b97a;
border-radius: 100%;
display: inline-block;
font-size: 12px;
width: 15px;
height: 15px;
line-height: 15px;
}
}
- 列表动态填充
<li
className="city-index-item"
key={item}>
<span className={activeIndex === index ? 'index-active' : ''}>
{item === 'hot' ? '热' : item.toUpperCase()}
</span>
</li>
实例
第一步:在src/views/City/index.js中
结构
{/* 右侧索引效果 */}
<ul className="city-index">
{this.renderRightIndex()}
</ul>
第二步:在src/views/City/index.css中
样式
.city-index {
position: absolute;
display: flex;
flex-direction: column;
right: 5px;
z-index: 1;
height: 90%;
box-sizing: border-box;
padding-top: 20px;
text-align: center;
.city-index-item {
flex: 1;
}
.index-active {
color: #fff;
background-color: #21b97a;
border-radius: 100%;
display: inline-block;
font-size: 12px;
width: 15px;
height: 15px;
line-height: 15px;
}
}
右侧初始样式
第三步:在src/views/City/index.js中,动态生成右侧索引列表
renderRightIndex = () => {
// 动态生成右侧索引列表
let { cityList, currentIndex } = this.state
if (cityList) {
let indexList = cityList.indexList
return indexList.map((item, index) => (
<li
key={index}
onClick={() => {
// 控制索引点击的列表定位
// 获取组件的实例对象,方便调用组件的实例方法
let list = this.listRef.current
// console.log(typeof list.scrollToRow)
// 控制列表滚动到当前索引的位置
list.scrollToRow(index)
}}
className="city-index-item">
<span className={currentIndex===index?'index-active': ''}>
{item==='hot'?'热': item.toUpperCase()}
</span>
</li>
))
}
}
第四步:后台返回数据初始效果
加工后台数据
- toUpperCase() 方法将字符串小写字符转换为大写
{item==='hot'?'热': item.toUpperCase()}
处理热和大写-效果
根据索引,判断高亮效果
constructor (props) {
super(props)
this.state = {
cityList: null,
currentIndex: 0 //默认索引为0
}
// 创建List组件的引用对象
this.listRef = React.createRef()
}
---------
let { cityList, currentIndex } = this.state
-------------
<span className={currentIndex===index?'index-active': ''}>
{item==='hot'?'热': item.toUpperCase()}
</span>
高亮效果