[英]How to pass additional parameters to onChange function in React
So, I've faced this problem: I have this type of Element here, obviously there's event when changing the input, is it possible to pass params like this and access event as well?所以,我遇到了这个问题:我在这里有这种类型的元素,显然在更改输入时有事件,是否可以传递这样的参数和访问事件? if so, how could I do it?
如果是这样,我该怎么做?
// this function accepts two other params index, stringValue
function onChange(index ,stringValue) {
console.log(event.target.value);
console.log("index?: " + index + " and value" + stringValue)
}
//this input is in Child Component
const index = 69;
const someRandomValue='iamstring';
<input defaultValue={name} onChange={onChange(index,iamstring)} />
You can use curried function to implement that.您可以使用柯里化函数来实现它。
onChange = (index, stringValue) => (event) => {
...
}
...
<input defaultValue={name} onChange={this.onChange(index,iamstring)} />
If you want you can make onChange into a function that returns another function.如果你愿意,你可以将 onChange 变成一个返回另一个函数的函数。
Then you can do something like this:然后你可以做这样的事情:
const Element = () => {
const index = 69;
const iamstring = 'iamstring';
const onChange = (index, stringValue) => event => {
console.log(event.target.value);
console.log('index?: ' + index + ' and value' + stringValue);
};
return <input defaultValue={name} onChange={onChange(index, iamstring)} />;
};
Bear in mind that the input's onChange
prop expects a function, so you can only execute a function inside the onChange
like this if that function is returning another function.请记住,输入的
onChange
道具需要一个函数,因此如果该函数返回另一个函数,您只能像这样在onChange
执行该函数。 (This is called a higher order function). (这称为高阶函数)。
You can convert the handler to a curried higher order function to return a function to be used as the callback that accepts the click event object您可以将处理程序转换为柯里化的高阶函数,以返回一个用作接受点击事件对象的回调函数
function onChange(index,stringValue) {
return (event) => {
console.log(event.target.value);
console.log("index?: " + index + " and value" + stringValue)
};
}
Or you can proxy the event object through to the callback, remember to add the event object as an argument to the handler或者您可以将事件对象代理到回调中,记住将事件对象作为参数添加到处理程序
function onChange(event, index ,stringValue) {
console.log(event.target.value);
console.log("index?: " + index + " and value" + stringValue)
}
<input defaultValue={name} onChange={e => onChange(e, index, iamstring)} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.