javascript - כיצד להעביר נתונים לפונקציה באופן מותנה באמצעות קורינג
אני די חדש בתכנות פונקציונלי. הנה הפרדיגמה הנוכחית שלי מהאפליקציה שלי ב-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 ולדחות את הביצוע. איך אני יכול לעשות את זה?
תשובה #1
פשוט תשתמש ב-props. בדוק אם ההורה העביר props מסוימים, במקרה שלך זה 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>
}
}
