How to implement sliding in react
React method to implement sliding: 1. Find touches in the onTouchStart event, and record the occurrence of new touches according to the identifier; 2. Record the coordinates of each point passed by the touch according to the identifier in the onTouchMove event; 3. In the onTouchEnd event, find the ending touch event, and then calculate the gesture to be performed based on the point crossed by the ending touch event.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to implement sliding in react?
react to achieve left and right sliding effects
React implementation of sliding gestures

Recently I did a little bit about the sliding page turning function of react on the mobile terminal.
I started searching and found that I couldn’t find a suitable library. The only library I found was a library named react-touch. At first glance, there were four to five hundred stars in the front-end world === I did it myself, and it didn’t seem like I wanted to If you want the function you want, forget about writing it yourself.
After looking at the principle, it basically works with the three events of onTouchStart, onTouchMove and onTouchEnd to record the sliding point and then calculate the gesture.
Obviously for multi-touch, you need to find the path of each touch point, so there are the following steps:
Find the touches in the onTouchStart event, and record the new ones according to the identifier The touch appears.
In the onTouchMove event, record the coordinates of each point passed by the touch based on the identifier.
In the onTouchEnd event, find the ending touch event, and then calculate the gesture to be performed by the point crossed by the ending touch event.
For me, I just want the function of sliding up and down, so I only focus on the single touch situation.
Next, prepare to write the code. Oh, no, first we have to think about how to encapsulate it. Start asking and answering yourself:
I want to use a singleton pattern.
Is it too troublesome to use? Do I need to instantiate it first?
Then use static classes?
If you already have js, what kind of static class is needed? Just output a dictionary and that’s it.
Okay then, let’s start masturbating.
Data part
const touchData = { touching: false, trace: [] }; // 单点触摸,所以只要当前在触摸中,就可以把划过的点记录到trace中了 function* idGenerator() { let start = 0; while (true) { yield start; start += 1; } } //这个生成器用来生成不同事件回调的id,这样我们可以注册不同的回调,然后在不需要的时候删掉。 const callbacks = { onSlideUpPage: { generator: idGenerator(), callbacks: {} }, onSlideDownPage: { generator: idGenerator(), callbacks: {} } }; //存储向上、下换页的回调函数
Record touch part
The events here deal with react's synthetic events, not native events.
function onTouchStart(evt) { if (evt.touches.length !== 1) { touchData.touching = false; touchData.trace = []; return; } touchData.touching = true; touchData.trace = [{ x: evt.touches[0].screenX, y: evt.touches[0].screenY }]; } //在onTouchStart事件,如果是多点触摸直接清空所有数据。如果是单点触摸,记录第一个点,并设置状态 function onTouchMove(evt) { if (!touchData.touching) return; touchData.trace.push({ x: evt.touches[0].screenX, y: evt.touches[0].screenY }); } //如果在单点触摸过程中,持续记录触摸的位置。 function onTouchEnd() { if (!touchData.touching) return; let trace = touchData.trace; touchData.touching = false; touchData.trace = []; handleTouch(trace); //判断touch类型并调用适当回调 } //在触摸结束事件,中调用handleTouch函数来处理手势判断逻辑并执行回调
handleTouch function
function handleTouch(trace) { let start = trace[0]; let end = trace[trace.length - 1]; if (end.y - start.y > 200) { Object.keys(callbacks.onSlideUpPage.callbacks).map(key => callbacks.onSlideUpPage.callbacks[key]() ); // 向上翻页 } else if (start.y - end.y > 200) { Object.keys(callbacks.onSlideDownPage.callbacks).map(key => callbacks.onSlideDownPage.callbacks[key]() ); // 向下翻页 } }
Here I only judged up and down Page two events, if the event is reached, all callbacks registered for the event will be called. If there are multiple callbacks, the execution order of the callbacks can be adjusted as needed. There should be no order here.
Interface part
function addSlideUpPage(f) { let key = callbacks.onSlideUpPage.generator.next().value; callbacks.onSlideUpPage.callbacks[key] = f; return key; } //注册向上滑动回调并返回回调id function addSlideDownPage(f) { let key = callbacks.onSlideDownPage.generator.next().value; callbacks.onSlideDownPage.callbacks[key] = f; return key; } //注册向下滑动回调并返回回调id function removeSlideUpPage(key) { delete callbacks.onSlideUpPage.callbacks[key]; } //使用回调id删除向上滑动回调 function removeSlideDownPage(key) { delete callbacks.onSlideDownPage.callbacks[key]; } //使用回调id删除向下滑动回调 export default { onTouchEnd, onTouchMove, onTouchStart, addSlideDownPage, addSlideUpPage, removeSlideDownPage, removeSlideUpPage }; //输出所有接口函数
There’s nothing to say, it’s just so simple and crude. Next, let’s use it in react!
Using in next.js
I use next.js create-next-app. Bind all touch events in the _app.js file in the pages directory.
//pages/_app.js import App, { Container } from "next/app"; import React from "react"; import withReduxStore from "../redux/with-redux-store"; import { Provider } from "react-redux"; import touch from "../components/touch"; class MyApp extends App { render() { const { Component, pageProps, reduxStore } = this.props; return ( <Container> <Provider store={reduxStore}> <div onTouchEnd={touch.onTouchEnd} onTouchStart={touch.onTouchStart} onTouchMove={touch.onTouchMove} > <Component {...pageProps} /> </div> { // 将所有导出的touch事件绑定在最外层的div上 // 这样就可以全局注册事件了 } </Provider> </Container> ); } } export default withReduxStore(MyApp);
Let’s see how to use it.
import React, {useEffect} from "react"; import touch from "../touch"; const Example = () => { useEffect(() => { let key = touch.addSlideDownPage(() => { console.log("try to slideDownPage!!") }); return () => { touch.removeSlideDownPage(key) // 用完别忘了删除事件 }; }, []); return ( <div>This is an example!!</div> ); };
Use in native react
This project is generated using create-react-app
//src/App.js import React from 'react'; import logo from './logo.svg'; import './App.css'; import touch from "./components/touch"; function App() { return ( <div className="App" onTouchEnd={touch.onTouchEnd} onTouchStart={touch.onTouchStart} onTouchMove={touch.onTouchMove} > <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); }
Conclusion
If someone really reads the code carefully, there may be a problem with the content in touch.js Except for using react's synthetic events, there is nothing else to do with react, which seems unconventional.
This is indeed the case, and it has nothing to do with react. The explanation is that these data do not need to be passed through react's state or redux's state. Firstly, in terms of performance, updating redux or react's state will trigger react's re-rendering, which is not necessary. Secondly, we hope that these interfaces can be used globally. So I didn’t use the react mechanism. In fact, this is like what react calls uncontrolled components.
Finally attached is the complete touch.js
//touch.js const touchData = { touching: false, trace: [] }; function* idGenerator() { let start = 0; while (true) { yield start; start += 1; } } const callbacks = { onSlideUpPage: { generator: idGenerator(), callbacks: {} }, onSlideDownPage: { generator: idGenerator(), callbacks: {} } }; function onTouchStart(evt) { if (evt.touches.length !== 1) { touchData.touching = false; touchData.trace = []; return; } touchData.touching = true; touchData.trace = [{ x: evt.touches[0].screenX, y: evt.touches[0].screenY }]; } function onTouchMove(evt) { if (!touchData.touching) return; touchData.trace.push({ x: evt.touches[0].screenX, y: evt.touches[0].screenY }); } function onTouchEnd() { if (!touchData.touching) return; let trace = touchData.trace; touchData.touching = false; touchData.trace = []; handleTouch(trace); } function handleTouch(trace) { let start = trace[0]; let end = trace[trace.length - 1]; if (end.y - start.y > 200) { Object.keys(callbacks.onSlideUpPage.callbacks).map(key => callbacks.onSlideUpPage.callbacks[key]() ); } else if (start.y - end.y > 200) { Object.keys(callbacks.onSlideDownPage.callbacks).map(key => callbacks.onSlideDownPage.callbacks[key]() ); } } function addSlideUpPage(f) { let key = callbacks.onSlideUpPage.generator.next().value; callbacks.onSlideUpPage.callbacks[key] = f; return key; } function addSlideDownPage(f) { let key = callbacks.onSlideDownPage.generator.next().value; callbacks.onSlideDownPage.callbacks[key] = f; return key; } function removeSlideUpPage(key) { delete callbacks.onSlideUpPage.callbacks[key]; } function removeSlideDownPage(key) { delete callbacks.onSlideDownPage.callbacks[key]; } export default { onTouchEnd, onTouchMove, onTouchStart, addSlideDownPage, addSlideUpPage, removeSlideDownPage, removeSlideUpPage };
Recommended learning: "react video tutorial"
The above is the detailed content of How to implement sliding in react. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.
