Optionally pass parameter to function being passed around

夙愿已清 提交于 2019-12-12 19:05:15

问题


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?


回答1:


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.




回答2:


Try to define your function as follows:

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

It will return a function that returns a date, with a default value of "MM/DD/YYYY".

So your component will be using this like

<TableColumn fromat={dateFormatter()}/>

or

<TableColumn fromat={dateFormatter("MM/DD")}/>


来源:https://stackoverflow.com/questions/47909062/optionally-pass-parameter-to-function-being-passed-around

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!