React JS 范围滑块 - 使用数组作为值?

A7D*_*7DC 5 javascript arrays range reactjs

我想知道您将如何使用 React 中的方法获取数组中索引的值input[type="range"],类似于此示例

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

正如您将从下面的示例代码中看到的,我最初渲染我想要的值(在本例中为“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"));
};
Run Code Online (Sandbox Code Playgroud)

链接到Codepen

Dan*_*ich 3

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

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

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

this.state = {
  value: 0
};
Run Code Online (Sandbox Code Playgroud)

接下来,在 jsx 主体中更改为:

{label} <b className="fw7 pl1">{this.props.value[value]}</b>
Run Code Online (Sandbox Code Playgroud)

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

工作代码笔