Javascript 如何将多个参数传递给输入的 onChange 处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29099610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass multiple parameters to input's onChange handler
提问by Piotr Perak
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:
这允许我编写 onChange 处理函数:
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:
但在这个处理程序中,我需要我想更改的范围对象的 id。所以我可以改变我在渲染函数中创建输入元素的方式并改变:
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
现在我的处理程序将接收 range.id 作为参数,但现在我没有 newName 值。我可以使用 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.
这是我知道的唯一解决方案,但我怀疑有更好的解决方案。
采纳答案by Alexandre Kirszenberg
The eventargument is still passed, but the rangeIdargument is prepended to the arguments list, so your changeRangeNamemethod would look like
该event参数还通过了,但rangeId参数前置到参数列表,让你的changeRangeName方法看起来像
changeRangeName: function (rangeId, event) {
var newName = event.target.value;
},
回答by EgorTitov
I think this way is easier:
我认为这种方式更容易:
<Input type="text"
value={range.name}
onChange={(e) => this.changeRangeName(range.id, e)}
...
onChange(id, e) {
...
}

