How to achieve page switching when sliding in React?
To achieve page sliding in React, you can use React’s event handling and CSS transition effects. Here is a simple example:
- First, you need to set a state in the React component to track the current page index.
import React, { useState } from "react";
const App = () => {
const [currentPage, setCurrentPage] = useState(0);
// ...
return (
<div>
{/* 页面内容 */}
</div>
);
};
export default App;
- beginning to touch
- dragging a finger across a touch screen
- end of touch action
import React, { useState } from "react";
const App = () => {
const [currentPage, setCurrentPage] = useState(0);
const handleTouchStart = (e) => {
// 记录滑动开始时的触摸位置
};
const handleTouchMove = (e) => {
// 计算滑动的距离
// 根据滑动距离来判断是否切换页面
};
const handleTouchEnd = (e) => {
// 清除触摸位置记录
};
return (
<div
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>
{/* 页面内容 */}
</div>
);
};
export default App;
- change
import React, { useState } from "react";
import "./App.css";
const App = () => {
const [currentPage, setCurrentPage] = useState(0);
const handleTouchStart = (e) => {
// 记录滑动开始时的触摸位置
};
const handleTouchMove = (e) => {
// 计算滑动的距离
// 根据滑动距离来判断是否切换页面
};
const handleTouchEnd = (e) => {
// 清除触摸位置记录
};
return (
<div
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
className="slider-container"
style={{
transform: `translateX(-${currentPage * 100}%)`,
transition: "transform 0.3s ease-in-out",
}}
>
{/* 第一页 */}
<div className="page">Page 1</div>
{/* 第二页 */}
<div className="page">Page 2</div>
{/* 第三页 */}
<div className="page">Page 3</div>
</div>
);
};
export default App;
- Finally, you need to add some CSS styles to define the page container and the styles of the page, as well as the styles for transition effects.
.slider-container {
display: flex;
width: 300%;
}
.page {
width: 33.33%;
}
.page:nth-child(1) {
background-color: #ff0000;
}
.page:nth-child(2) {
background-color: #00ff00;
}
.page:nth-child(3) {
background-color: #0000ff;
}
By following the steps above, you can achieve the effect of sliding between pages in React. As the user slides on the screen, the pages will switch based on the distance of the slide, and a transition effect will be added to make the switching smoother.