如何在React中向onChange函数传递额外的参数

3

所以,我遇到了这个问题:我有这种 Element 类型的元素,当输入改变时,显然会触发事件,能否像这样传递参数,并访问事件呢?如果可以,我该怎么做呢?

// 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)} />
3个回答

7
你可以使用柯里化函数来实现这个功能。
onChange = (index, stringValue) => (event) => {
...
}

...

<input defaultValue={name} onChange={this.onChange(index,iamstring)} />

2
你可以将处理程序转换为柯里化的高阶函数,返回一个函数作为回调使用,该函数接受点击事件对象。
function onChange(index,stringValue) {
  return (event) => {
    console.log(event.target.value);
    console.log("index?: " + index + " and value" + stringValue)
  };
}

或者你可以通过代理事件对象到回调函数中,记得将事件对象作为处理程序的参数添加。

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)} />

1

如果你愿意,你可以将onChange转换为一个返回另一个函数的函数。

然后你可以像这样做:

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)} />;
};


请牢记,输入框的 onChange 属性期望一个函数,因此只有当该函数返回 另一个 函数时,您才能在 onChange 中执行函数。这被称为高阶函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接