reactjs - 显示不是功能
问题描述
我有一个带有显示功能的员工类,然后在尝试实现原型模式时,尝试使用克隆对象中的显示功能时出现错误。
员工类代码:
类员工{
private totalperMonth: number;
private name: string;
private hiredDate: Date;
public dailyRate: number;
constructor(name: string, hiredDate: Date, dailyRate: number){
this.totalperMonth = dailyRate * 20 ;
}
public display(): string{
return "Employee " + this.name + " earns per month: " + this.totalperMonth;
}
public clone():Employee{
var cloned = Object.create(Employee || null);
Object.keys(this).map((key: string) => {
cloned[key]= this[key];
});
return <Employee>cloned;
}
}
export default Employee;
组件代码:
import * as React from 'react';
import styles from './Prototype.module.scss';
import { IPrototypeProps } from './IPrototypeProps';
import { escape } from '@microsoft/sp-lodash-subset';
import Employee from './Employee';
export default class Prototype extends React.Component<IPrototypeProps, {}> {
public render(): React.ReactElement<IPrototypeProps> {
const today = new Date();
let employee1: Employee = new Employee('Luis', today, 500);
let employee2 = employee1.clone();
employee2.dailyRate = 550;
return (
<div className={ styles.prototype }>
<div className={ styles.container }>
<div className={ styles.row }>
<div className={ styles.column }>
<span className={ styles.title }>Welcome to SharePoint!</span>
<p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>
<p className={ styles.description }>{escape(this.props.description)}</p>
<span className={ styles.label }>{employee1.display()}</span>
<span className={ styles.label }>{employee2.display()}</span>
</div>
</div>
</div>
</div>
);
}
}
解决方案
你可以试试这个:
clone():Employee {
return Object.assign(Object.create(Object.getPrototypeOf(Employee)), this)
}
这将基于当前对象类创建一个新对象,同时还使用您之前拥有的数据填充数据。
您的解决方案实际上并没有使其成为 Employee,因为它只是一个克隆的普通对象。
推荐阅读
- python - 尝试从应用程序导入模型会引发 ImproperlyConfigured 异常
- jenkins - 在詹金斯中实现长时间运行的作业的惯用方法是什么?
- javascript - useEffect 中的 js 承诺链是否保证在被垃圾收集之前完成?
- javascript - 对象数组 (JS) - 如何将第一个对象的内容复制到第二个对象中?
- python - 我需要这个循环来允许 3 个人输入信息,然后打印出带有列表的信息
- laravel - Laravel RouteServiceProvider.php 文件
- css - 基于行 onclick 动态呈现模式 - ReactJS
- f# - 是否可以在 F# 中将对象属性提取为序列
- c - 在 C 中写入和读取二进制文件的问题
- google-cloud-platform - 将 Python 库从 Cloud Source Repository 安装到 Cloud Run 容器