react 滑块 组件
by Rajesh Pillai
由Rajesh Pillai
如何仅使用<div>和<span>从零开始在React中构建范围滑块组件 (How to build a range slider component in React from scratch using only <div> and <span>)
In this article we will build a React range slider component step by step using only <div>. We will enable it with touch support.
在本文中,我们将仅使用<div>逐步构建一个React range滑块组件。 我们将通过触摸支持启用它。
What can you do with a piece of about 50 <div’s>?
一块约50个<div's可以做什么?
Build a slider control from scratch. If this sounds interesting, then follow along.
从头开始构建一个滑块控件。 如果听起来很有趣,请继续。
The final output will look like the below animation.
最终输出将类似于以下动画。
Please do note that I have developed this component as a teaching exercise for my students of ReactJS — Beyond the Basics course on Udemy, so it may have some edge cases (which I will fix as and when encountered).
请注意,我已经将这个组件开发为我的ReactJS学生的教学练习-除了有关Udemy的基础课程之外 ,因此它可能会有一些极端情况(我会在遇到问题时予以解决)。
You could use an HTML5 range control and customize it. But I wanted to take a different approach and build something from scratch. And the result is what you see here.
您可以使用HTML5范围控件并对其进行自定义。 但是我想采用一种不同的方法,并从头开始构建一些东西。 结果就是您在这里看到的。
Our slider component will be composed of the below three elements:
我们的滑块组件将由以下三个元素组成:
- A slider range 滑块范围
- The actual slider controls 实际的滑块控件
- The current selection range 当前选择范围
为我们的组件定义状态 (Defining the state for our component)
Let us begin by defining our state. I am only showing you the important part of the code. For the full source code, please refer to the link at the end of the article.
让我们从定义状态开始。 我只向您展示代码的重要部分。 有关完整的源代码,请参阅本文结尾处的链接。
state = { slots: 24, start: 0, end: 10, labelMode: "mid", // mid, long}
The state contains the following properties.
该状态包含以下属性。
- slots: Total slots to be drawn (in this case I am using it as a time selector, so it will have 24 hour slots) slot:要绘制的总时隙(在这种情况下,我将其用作时间选择器,因此它将有24小时)
- start: The start value of the selection start:选择的起始值
- end: The end value of the selection end:选择的结束值
- labelMode: Currently unused. But can be used to customize the scale label rendering. labelMode:当前未使用。 但是可用于自定义比例标签渲染。
render方法的返回部分 (The return part of the render method)
Let us now take a look at the return part of the render method. The render() method will be slowly composed of small pieces o