React实现二级联动(左右联动)
本文实例为大家分享了React实现二级联动的具体代码,供大家参考,具体内容如下
js代码
import { Component } from 'react'import './linkage.less'class Linkage extends Component {constructor(...args) {super(...args)// 添加左侧this.FnButtonList = []//添加右侧this.FnContentList = []// 开关this.ScrollBys = true// 在constructor中直接执行——>react更新时才会渲染——>componentDidMount时才能触发获取this.init()}init() {this.FnSetButton(20)// 右侧的渲染this.FnSetContent(20)this.state = {ButtonList: this.FnButtonList,ContentList: this.FnContentList,// 下标ButtonListIndex: 0,}}componentDidMount() {this.EveryHeight = this.refs['linkage-button-list'].children[0].offsetHeight}// 随机数FnSetRandom(m, n) {return parseInt(Math.random() * (m - n) + n); }// 渲染左侧的按钮FnSetButton(n) {for (var i = 0; i < n; i++) {this.FnButtonList.push({id: `按钮${i}`,text: `按钮${i}`})}}// 渲染右侧内容FnSetContent(n) {let ContTop = 0; //第一个元素距离页面顶部的距离let Random = this.FnSetRandom(750, 1400)for (let i = 0; i < n; i++) {this.FnContentList.push({height: Random,id: `内容${i}`,text: `内容${i}`,top: ContTop,}); ContTop += Random; }}Fncurrn(index) {if (index > 3) {this.refs["linkage-button"].scrollTop = (index - 3) * this.EveryHeight; }if (index <= 3) {this.refs["linkage-button"].scrollTop = 0; }}// 点击FnButtonTab(index) {this.ScrollBys = falsethis.setState({ButtonListIndex: index})this.refs["linkage-content"].scrollTop = this.state.ContentList[index].top; //点击居中this.Fncurrn(index)}//右边滚动左边FnScroll(ev) {this.ContTop = ev.target.scrollTopif (this.ScrollBys) {let n = 0for (let i = 0; i < this.state.ContentList.length; i++) {if (this.refs["linkage-content"].scrollTop >= this.state.ContentList[i].top) {//盒子滚动的距离如果大于右边盒子里的元素距离页面顶部的距离n = i; }}this.setState({ButtonListIndex: n})if (Math.abs(n - this.state.ButtonListIndex) === 1) {this.setState({ButtonListIndex: n})//滚动居中this.Fncurrn(n)}}if (this.ContTop == this.state.ContentList[this.state.ButtonListIndex].top) {this.ScrollBys = true}}render() {return ({this.state.ButtonList.map((item, index) => {item.text})}{this.state.ContentList.map((item) => {item.text})}