javascript - 如何使用柯里化(Currying)有条件地将数据传递给函数

标签 javascript typescript functional-programming

我对函数式编程有些陌生。这是我的 React 应用程序中的当前范例。我有一个通用组件,我正在向其中传递一个函数,该函数可以选择采用 placeholder 参数。

<TableColumn field="effectiveDate" format={dateFormatter} sortable>Start Date</TableColumn>
<TableColumn field="endDate" format={dateFormatter("No End Date")} sortable>End Date</TableColumn> 

我认为我需要使用柯里化(Currying)来实现我的目标(稍后我会谈到)。既然如此,我就这样定义了 dateFormatter:

export function dateFormatter(placeholder?: string) {
  return function (date: string) {
    const attributes: any = { value: date };
    if (placeholder) {
      attributes.placeholder = placeholder;
    }
    return <ShortDate {...attributes} />;
  };
}

然后,当我实际呈现我的表格时,我循环遍历每条记录并获取如下值:

getRecordValue(record: any, column: React.ReactElement<TableColumnProps>) {
    const { format, field } = column.props;
    const cell = field ? record[field] : "";
    if (format) {
      return format()(cell, record);
    }
    return cell;
}

我想要一个单一的 dateFormatter 函数,但能够选择性地传递一个 placeholder 并延迟执行。我该怎么做?

最佳答案

只需使用 Prop 。检查父级是否传递了某些 Prop ,在您的情况下是 format

class App extends React.component{
  render(){
     <CustomComponent  format={dateFormatter("No End Date")}/>
  }
}

class CustomComponent extends React.component{
  constructor(props){
    super(props)
  }

  render(){
     <div>
       Your content maybe
       { this.props.format && this.props.format }
     </div>
  }
}

关于javascript - 如何使用柯里化(Currying)有条件地将数据传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47894331/

相关文章:

javascript - Jquery .append() chop 输出到 div

Python 和函数式编程 : is there an apply() function?

javascript - jQuery - 在变量元素内引用伪/其他类

javascript - 如何测试 Javascript 对象是否具有给定名称的方法?

javascript - 使用 .find() 时忽略空值

reactjs - 为什么在使用useCallback时使用 'ref'而不是直接使用useCallback

exception - 如何在 Clojure 中抛出异常?

javascript - JavaScript 是否有像 "range()"这样的方法来生成提供的范围内的范围?

javascript - d3 linkHorizo​​ntal 用于直线曲线

angular - 如何在 HttpClient "get"方法中传递 URLSearchParams - Angular 5