0

I want to create three input[type=range], but I just can't use onChange={this.handleChange}, there will be mistakes. If I change to {elem.handleChange}, there will be no mistake, but I still can't get the value.

var ColorBoard = React.createClass({
        getInitialState() {
            return {
                inputItems:[
                    {id:1, value:0},
                    {id:2, value:5},
                    {id:3, value:10}
                ]
            };
        },
        handleChange(event){
            console.log(event.target.value)
        },
        render() {
            var displayInput = this.state.inputItems.map(function(elem) {
                return <input type="range" min="0" max="255" id={elem.id} onChange={this.handleChange} />;
            });
            return (
                <div className="well clearfix">
                    {displayInput}
                    <span>{this.state.inputItems[0].value},{this.state.inputItems[1].value},{this.state.inputItems[2].value}</span>
                    <button onClick={this.handleChange}>Click</button>
                </div>
            );
        }
    });
Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
Sean Wang
  • 3
  • 1

1 Answers1

0

Because you didn't specify the this pointer for map, so this will refer to the global scope.

Either:

  1. Specify the this pointer: displayInput = this.state.inputItems.map(fn, this);
  2. Use an arrow function
  3. Capture self in the closure

Like so:

var self = this;
var displayInput = this.state.inputItems.map(function(elem) {
  return <input type="range" min="0" max="255" id={elem.id} onChange={self.handleChange} />;
});
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
  • Please mark such questions as duplicate instead of answering them, there are hundreds or questions related to binding on stackoverflow – Shubham Khatri Jan 04 '18 at 06:31