簡體   English   中英

如何使用curring有條件地將數據傳遞給函數

[英]How to conditionally pass data into a function using currying

我對函數式編程有些陌生。 這是我當前的React應用范例。 我有一個通用組件,要向其中傳遞一個函數,該函數可以選擇使用placeholder參數。

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

我相信我需要用粗俗的話來實現我的目標(稍后我會講)。 既然如此,我就這樣定義了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並推遲執行。 我怎樣才能做到這一點?

只是使用道具。 檢查您的父母是否通過了某些道具,在您的情況下為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>
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM