可以将参数传递给正在传递的函数 [英] Optionally pass parameter to function being passed around

查看:100
本文介绍了可以将参数传递给正在传递的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 导出函数dateFormatter(date:string){
return moment(date ).format( MM / DD / YYYY);
}

我有一个React组件,我可以像这样传递函数:

 < TableColumn field =endDateformat = {dateFormatter}>结束日期< / TableColumn> 

该组件调用如下函数:

  const {format,field} = column.props; 
if(format){
return format(cell);
}
return cell;

所有这些工作都很好。我现在想改变我的 dateFormatter 函数,这样我可以选择性地将一个参数传递给它。我不清楚如何做到这一点,因为如果我将引用更改为:

 < TableColumn field =endDateformat = {dateFormatter(MM / YY)}>结束日期< / TableColumn> 

它会将该格式作为日期传递给我的函数。



我该如何可选地将一个参数传递给一个函数,然后传递给它?

解决方案

导出一个执行格式化的函数,导出制作的函数作为函数:

  export function makeFormatter (format:string){
return function(date:string){
return moment(date).format(format ||MM / DD / YYYY);
};
}

当您使用该函数时,您会插入 call 转换为 makeFormatter()所需的格式(或没有任何内容可以获得默认值)。您当然可以预先制作几种不同的格式化函数以方便使用:

  var formatters = {
mmddyyyy:makeFormatter( MM / DD / YYYY),
euro:makeFormatter(DD / MM / YYYY),
datetime:makeFormatter(MM / DD / YYYY hh:mm),
// etc
};

然后您可以使用 formatters.mmddyyyy 获取该格式化程序的代码。


I have the following function:

export function dateFormatter(date: string) {
  return moment(date).format("MM/DD/YYYY");
}

I have a React component where I'm able to pass the function like this:

<TableColumn field="endDate" format={dateFormatter}>End Date</TableColumn>

That component calls the function like this:

const { format, field } = column.props;
if (format) {
  return format(cell);
}
return cell;

All of this works fine. I would now like to alter my dateFormatter function so that I can optionally pass a parameter into it. I'm unclear on how to do this because if I change the reference to:

<TableColumn field="endDate" format={dateFormatter("MM/YY")}>End Date</TableColumn>

It will pass that format as the date into my function.

How can I optionally pass a parameter into a function that I will then pass around?

解决方案

Instead of exporting a function that does the formatting, export a function that makes a function:

export function makeFormatter(format: string) {
  return function(date: string) {
    return moment(date).format(format || "MM/DD/YYYY");
  };
}

When you use the function, you'll insert a call to makeFormatter() with the desired format (or nothing to get the default). You could of course pre-make several different formatting functions for convenience:

var formatters = {
  mmddyyyy: makeFormatter("MM/DD/YYYY"),
  euro: makeFormatter("DD/MM/YYYY"),
  datetime: makeFormatter("MM/DD/YYYY hh:mm"),
  // etc
};

Then you can use formatters.mmddyyyy in the code to get that formatter.

这篇关于可以将参数传递给正在传递的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆