Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

javascript - How to pass multiple parameters to input's onChange handler

I render collection of input elements for objects in array.

render: function() {
    var ranges = [];
    this.props.ranges.map(function(range, index) {
        var rangeElement = <Input type="text"
            value={range.name} onChange={this.changeRangeName.bind(this)} />
        ranges.push(rangeElement);
    }, this);

    // render ranges
}

this allows me to write onChange handler function:

changeRangeName: function (event) {
    var newName = event.target.value;
},

but in this handler I need id of range object I want to change. So I could change change how I create input elements in render function and change:

var rangeElement = <Input type="text"
            value={range.name}
            onChange={this.changeRangeName.bind(this, range.id)} />

Now my handler will receive range.id as parameter but now I don't have the newName value. I can get it using refs

var rangeElement = <Input type="text"
            ref={'range' + range.id}
            value={range.name}
            onChange={this.changeRangeName.bind(this, range.id)} />

This is the only solution I know but I suspect there is better one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this way is easier:

    <Input type="text"
                value={range.name}
                onChange={(e) => this.changeRangeName(range.id, e)}
        ...
    onChange(id, e) {
        ...
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...