【问题标题】:How to pass additional parameters to onChange function in React如何将附加参数传递给 React 中的 onChange 函数
【发布时间】:2020-10-12 18:56:34
【问题描述】:

所以,我遇到了这个问题:我这里有这种类型的元素,显然在更改输入时有事件,是否可以传递这样的参数并访问事件?如果是这样,我该怎么做?

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

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    您可以使用 curried 函数来实现它。

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

      【讨论】:

        【解决方案3】:

        如果你愿意,你可以将 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 属性需要一个函数,因此如果该函数返回 另一个 功能。 (这称为高阶函数)。

        【讨论】:

          猜你喜欢
          • 2013-06-03
          • 2016-04-26
          • 1970-01-01
          • 1970-01-01
          • 2015-07-19
          • 2014-11-27
          • 1970-01-01
          • 2015-08-16
          • 2015-03-03
          相关资源
          最近更新 更多