【问题标题】:React JS range slider - using an array for the value?React JS范围滑块-使用数组作为值?
【发布时间】:2018-02-04 08:51:18
【问题描述】:

我想知道如何在 React 中使用 input[type="range"] 来获取数组中索引的值,类似于 this example

我想要做的是:传入一系列值,并能够通过使用数组的索引打印出这些值。

正如您从下面的示例代码中看到的那样,我最初渲染的是我想要的值(在本例中为“Apples”),但是当我使用幻灯片时,它开始渲染数组的索引,而不是值。

这是我目前得到的:

class RangeSlider extends React.Component {
  // constructor
  constructor(props) {
    super(props);
    this.state = {
      value: props.value[0]
    };
  }

  handleChange(event, index) {
    const { value } = this.state;
    this.setState({ value: event.target.value});
  }

  render() {
    const { value } = this.state;
    const { label } = this.props;

    return (
      <div className="mb4">
        <label className="f4 mt0">
          {label} <b className="fw7 pl1">{value}</b>
        </label>
        <input
          className="w-100 appearance-none bg-transparent range-slider-thumb-custom"
          type="range"
          min={0}
          max={this.props.value.length - 1}
          step={1}
          value={value}
          onChange={this.handleChange.bind(this)}
        />
      </div>
    );
  }

}

window.onload = () => {
  ReactDOM.render(
    <RangeSlider 
      label={"I would like some "} 
      value={["Apples", "Oranges", "Pears"]} />, 
    document.getElementById("main"));
};

链接到a Codepen

【问题讨论】:

标签: javascript arrays reactjs range


【解决方案1】:

您遇到的唯一问题是在初始加载时,您的状态对象被设置为正确访问数组中的值。但是,每次触发 handleChange 方法时,它都会用一个整数覆盖状态,因此不会执行您所期望的操作。

如果您只是将状态对象中的“value”属性设置为默认值“0”,则只需跟踪索引,并在代码中再更改一行,它应该可以正常工作。

首先将您的状态更改为如下所示:

this.state = {
  value: 0
};

接下来,在你的 jsx 正文中更改为:

{label} <b className="fw7 pl1">{this.props.value[value]}</b>

这样,您总是会在屏幕上打印出一个值,而不是一个整数。我认为这导致您必须添加更少的代码。

Working Codepen.

【讨论】:

  • 谢谢你,丹尼尔。由于代码的简单性和详细的解释,我已经接受了这个作为正确答案。这完全有道理,干杯!
  • 没问题。爱我一些反应。让问题出现在 SO =D
【解决方案2】:

这是更新后的代码

import React from 'react'

class Range extends React.Component {
  // constructor
  constructor(props) {
    super(props)
    this.state = {
      value: 0
    }

    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(event) {
    this.setState({ value: this.props.value[event.target.value]})
  }

  render() {
    const { value } = this.state
    const { label } = this.props
    return (
      <div className="mb4">
        <label className="f4 mt0">
          {label} <b className="fw7 pl1">{value}</b>
        </label>
        <input
          className="w-100 appearance-none bg-transparent range-slider-thumb-custom"
          type="range"
          min={0}
          max={this.props.value.length - 1}
          step={1}
          onChange={this.handleChange}
        />
      </div>
    )
  }

}

export default Range

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多