这里包了两个大盒子,外面的设置x轴溢出滚动属性,里面的大盒子设置的宽度比外面的盒子要大,然后js使用scrollTo设置left值实现滚动,设置属性behavior的值为smooth实现平滑过渡。这里需要用到smollscroll-polyfill插件,如果没有使用这个插件,ios平滑过渡会不管用。
tsx中
import { Component, createRef } from "react";
import './index.less';
import smoothscroll from "smoothscroll-polyfill";
interface Props {
}
interface State {
buttonList: ButtonList[],
contentList: ContentList[],
Index: number
}
interface ButtonList {
id: string,
text: string
}
interface ContentList {
id: string,
text: string
}
class Slide extends Component<Props, State>{
ContentWrap=createRef<HTMLDivElement>();
Content=createRef<HTMLDivElement>();
constructor(props: Props) {
super(props);
this.state = {
buttonList: [
{
id: 'b1',
text: '按钮1'
},
{
id: 'b2',
text: '按钮2'
},
],
contentList: [
{
id: 'c1',
text: '内容1'
},
{
id: 'c2',
text: '内容2'
},
],
Index: 0
}
}
Cut(index: number) {
smoothscroll.polyfill();
this.setState({
Index: index
})
let Left = (this.getContent().children[index] as HTMLDivElement).offsetLeft;
this.getContentWrap().scrollTo({left:Left,behavior:"smooth"})
}
getContentWrap(){
return this.ContentWrap.current as HTMLDivElement;
}
getContent(){
return this.Content.current as HTMLDivElement;
}
componentDidMount() {
}
render() {
return (
<div className="tab">
{this.state.buttonList.map((item, index) =>
<button onClick={this.Cut.bind(this, index)} className={this.state.Index === index ? "ac" : ""} key={item.id}>{item.text}</button>
)}
<div className="content-wrap" ref={this.ContentWrap}>
<div className="content" ref={this.Content}>
{this.state.contentList.map((item) =>
<div className="content-list" key={item.id}>{item.text}</div>
)}
</div>
</div>
</div>
)
}
}
export default Slide;
less
.tab{
button.ac{
background: red;
}
.content-wrap{
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
touch-action: none;
/* 解决ios滑动不流畅问题 */
transition: 0.3s ease-in all;
.content{
width: 200vw;
display: flex;
.content-list{
// display: inline-block;
width: 1000px;
height: 300px;
border:1px solid #ccc;
margin: 0 auto;
}
}
}
.content-wrap::-webkit-scrollbar {
display: none;
/* Chrome Safari */
}
}