渲染城市列表
目标
- 完成城市索引高亮效果
- 完成点击索引跳转到对应位置
- 能够实现切换城市功能(除了北京,上海,广州,深圳,其他成均无房源信息,需要提示用户)
城市索引列表高亮
- 给list组件添加onRowsRendered配置项,用于获取当前列表渲染的行信息,在里面就会有相应信息
- 通过参数 startIndex 获取到 起始行对应的索引号
- 判断 startIndex 和 activeIndex 不同时候,更新状态 activeIndex为 startIndex
<List
...
onRowsRendered={this.rowRendered}
/>
/**
* 获取滚动时候,相应的数据
* @param {*} param0
*/
rowRendered = ({ startIndex }) => {
if (this.state.activeIndex !== startIndex) {
this.setState({
activeIndex: startIndex
})
}
}
点击索引置顶该索引城市
-
给索引列表绑定点击事件
-
在点击事件中,通过index获取到当前项索引号
-
调用List组件的 scrollToRow方法,让List组件滚动到指定行
- 在constructor中,调用React.createRef() 创建ref对象
- 将创建好的ref对象,添加为List组件的ref属性
- 通过ref的current属性,获取到组件实例,再调用组件的scrollToRow方法
-
设置List组件的scrollToAlignment配置项值为start,保证点击行出现在页面顶部
-
对于点击索引无法正确定位的问题,调用List组件的 measureAllRows 方法,提前计算高度来解决
// 核心代码
constructor() {
...
this.listComponent = React.createRef()
}
async componentDidMount() {
await this.getCityList()
// 计算List组件高度
this.listComponent.current.measureAllRows()
}
renderCityIndex() {
return this.state.cityIndex.map((item, index) => {
return (
<li className="city-index-item" key={item} onClick={() => {
// 拿到List组件的实例
this.listComponent.current.scrollToRow(index)
}}>
...
</li>
)
})
}
render() {
return (
<div className="citylist">
...
{/* 城市列表 */}
<AutoSizer>
{
({ width, height }) => {
return <List
ref={this.listComponent}
...
/>
}
}
</AutoSizer>
...
</div>
)
}
切换城市
- 给城市列表项绑定事件
- 判断当前城市是否有房源数据
- 如果有房源数据,则保持当前城市数据到本地缓存中,并返回上一页
- 如果没有房源数据,则提示用户:改城市暂无房源数据,不执行任何操作
const HOST_CITY = ['北京', '上海', '广州', &