如何包装函数以添加新参数

How to wrap a function to add a new parameter

我有一个组件需要像 属性 这样的函数,其中发送一个参数 'value'

function myLoadOptions(value)  {
    fetch( (...)
    .then( (...) return data.options)
}


<Component
loadOptions = myLoadOptions

/>

但我需要添加 o 包装函数以添加新参数,如下所示:

function myLoadOptions(table, value)  {
    fetch( (...)
    .then( (...) return data.options)

}
let table = 'customers';
<Component
loadOptions = myLoadOptions(table)
/>

但它不起作用,loadOptions 不被 table 读取,有一种包装方法可以做到吗?

关于原始组件的更多信息: https://github.com/JedWatson/react-select

import { Async } from 'react-select';

/*
 * assuming the API returns something like this:
 *   const json = [
 *      { value: 'one', label: 'One' },
 *      { value: 'two', label: 'Two' }
 *   ]
 */

const getOptions = (input) => {
  return fetch(`/users/${input}.json`)
    .then((response) => {
      return response.json();
    }).then((json) => {
      return { options: json };
    });
}

<Async
  name="form-field-name"
  value="one"
  loadOptions={getOptions}
/>

在您的 render 中试试这个:

let table = 'customers';
...
<Component loadOptions={() => myLoadOptions(table) }/>

尝试将第一个参数绑定到函数,如下所示:

<Component
  loadOptions={myLoadOptions.bind(null, table)}
/>

其他选项将是一个包装器,就像 margaretkru 所建议的那样,但稍微改变一下以传递第二个参数:

<Component loadOptions={(value) => myLoadOptions(table, value) }/>