【发布时间】:2019-10-23 05:25:52
【问题描述】:
我在 react 中使用 https://github.com/locomotivemtl/locomotive-scroll 插件来启用平滑滚动。我试图让它做一个连续滚动,所以无论你向哪个方向滚动,它都会循环,通过在状态数组中添加和删除项目来改变顺序。
这可行,但会导致一些超级闪烁。
几个演示是
https://codesandbox.io/s/heuristic-resonance-0ybkl
https://codesandbox.io/s/young-wind-ozeeq
https://codesandbox.io/s/patient-darkness-6gxj1
任何帮助将不胜感激
代码如下
import React from "react";
import ReactDOM from "react-dom";
import LocomotiveScroll from "locomotive-scroll";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
limit: null,
items: [
"https://www.fillmurray.com/640/460",
"https://www.fillmurray.com/g/640/560",
"https://www.fillmurray.com/640/760",
"https://www.fillmurray.com/g/640/860",
"https://www.fillmurray.com/640/160",
"https://www.fillmurray.com/g/640/260",
"https://www.fillmurray.com/g/640/360",
"https://www.fillmurray.com/g/640/460"
]
};
}
componentDidMount() {
const target = document.querySelector("#view");
const scroll = new LocomotiveScroll({
el: target,
smooth: true,
smoothMobile: true,
getDirection: true
});
scroll.on("scroll", obj => {
console.log(obj.scroll.y);
if (this.state.limit !== null) {
if (obj.direction === "up") {
var current = this.state.items;
var first = current.shift();
current.push(first);
this.setState(
{
items: current
},
() => {
scroll.update();
}
);
}
if (obj.direction === "down") {
current = this.state.items;
var last = current.pop();
current.unshift(last);
this.setState(
{
items: current
},
() => {
scroll.update();
}
);
}
} else {
var halfway = obj.limit / 2;
scroll.scrollTo(target, halfway);
this.setState({
limit: obj.limit
});
}
});
scroll.scrollTo(target, 1);
}
render() {
return (
<div className="App">
<div id="view">
<div className="left">
{this.state.items.map(item => {
return <img src={item} alt="" />;
})}
</div>
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
【问题讨论】:
-
你能把你的代码也放在问题本身吗?这将使它对未来的访问者更有价值。
标签: javascript reactjs scroll