68 lines
1.4 KiB
JavaScript
68 lines
1.4 KiB
JavaScript
import React from 'react'
|
|
|
|
import './RangeInput.css'
|
|
|
|
export class RangeInput extends React.Component {
|
|
constructor(props) {
|
|
super(props)
|
|
this.state = {
|
|
rangeValue: props.value
|
|
? this.indexOfValue(props.value)
|
|
: Math.floor((this.length - 1) / 2)
|
|
}
|
|
this.handleChange = this.handleChange.bind(this)
|
|
}
|
|
|
|
get options() {
|
|
let { min, max, step } = this.props
|
|
let arr = []
|
|
if (step <= 0 || max < min) return []
|
|
for (min; min <= max; min += step) {
|
|
arr.push(min)
|
|
}
|
|
return arr.map(val => Math.round(val * 1000) / 1000)
|
|
}
|
|
|
|
get length() {
|
|
return this.options.length
|
|
}
|
|
|
|
get realValue() {
|
|
return this.options[this.state.rangeValue]
|
|
}
|
|
|
|
indexOfValue(value) {
|
|
let i = 0
|
|
for (let opt of this.options) {
|
|
if (opt >= value) return i
|
|
i++
|
|
}
|
|
return i
|
|
}
|
|
|
|
handleChange(e) {
|
|
this.setState({ rangeValue: e.target.value })
|
|
if (this.props.onChange) {
|
|
this.props.onChange(this.options[e.target.value])
|
|
}
|
|
}
|
|
|
|
render() {
|
|
return (
|
|
<div className="range-input">
|
|
<label>
|
|
<span>{this.props.label ? this.props.label : this.props.name}:</span>
|
|
<span>{Number(this.realValue.toFixed(2))}</span>
|
|
<input
|
|
type="range"
|
|
min={0}
|
|
max={this.length - 1}
|
|
value={this.state.rangeValue}
|
|
onChange={this.handleChange}
|
|
/>
|
|
</label>
|
|
</div>
|
|
)
|
|
}
|
|
}
|