[英]How to conditionally pass data into a function using currying
I'm somewhat new to functional programming. 我对函数式编程有些陌生。 Here is my current paradigm from my React app.
这是我当前的React应用范例。 I have a generic component into which I'm passing a function which can optionally take a
placeholder
argument. 我有一个通用组件,要向其中传递一个函数,该函数可以选择使用
placeholder
参数。
<TableColumn field="effectiveDate" format={dateFormatter} sortable>Start Date</TableColumn>
<TableColumn field="endDate" format={dateFormatter("No End Date")} sortable>End Date</TableColumn>
I believe I need to use currying to acheive my goal (which I'll speak to shortly). 我相信我需要用粗俗的话来实现我的目标(稍后我会讲)。 That being the case, I've defined
dateFormatter
like this: 既然如此,我就这样定义了
dateFormatter
:
export function dateFormatter(placeholder?: string) {
return function (date: string) {
const attributes: any = { value: date };
if (placeholder) {
attributes.placeholder = placeholder;
}
return <ShortDate {...attributes} />;
};
}
Then, when I actually render my table, I loop through each record and get the value like this: 然后,当我实际渲染表时,我遍历每条记录并获得如下值:
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;
}
I want to have a single dateFormatter
function, but be able to optionally pass a placeholder
and defer execution. 我希望有一个
dateFormatter
函数,但可以选择传递一个placeholder
并推迟执行。 How can I do this? 我怎样才能做到这一点?
just use props. 只是使用道具。 Check if the parrent has passed certain props, in your case is
format
. 检查您的父母是否通过了某些道具,在您的情况下为
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.