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

时间:2018-01-16 16:06:56

标签: javascript reactjs react-select

我有一个需要像属性这样的函数的组件,其中发送参数'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,有一种包装方式可以做到吗?

有关原始组件的更多信息: 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}
/>

2 个答案:

答案 0 :(得分:1)

render

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

答案 1 :(得分:0)

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

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

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

<Component loadOptions={(value) => myLoadOptions(table, value) }/>
相关问题