获取新的类实例作为默认道具



我有一个表单组件,它通过props获得一个名为Experience的自定义类。用户填写表单,组件在给定的类实例上写入更改,然后调用名为onExperienceChange的函数prop。当组件没有经验时,它只会创造一个新的。我使用默认的道具,我想知道是否有一种方法来获得新的类实例与默认的道具。

我现在拥有的:

class ExperienceForm extends React.Component {
constructor(props) {
super(props);
if (this.props.experience === undefined)
this.experience = new Experience("Experience", "");
else
this.experience = this.props.experience;
}

我想让它看起来像:

class ExperienceForm extends React.Component {
static defaultProps = {
experience = {new Experience("Experience", "")} // it has to create new Experience each time
}
constructor(props) {
super(props);
this.experience = this.props.experience;
}

或者像这样:

class ExperienceForm extends React.Component {
constructor(props, experience = new Experience("Experience", "")) {
super(props);
this.experience = experience;
}

这是Experience类的样子:

class Experience {
constructor(
header, 
description, 
startDate = "",
endDate = "",
headerIcon = null, 
headerDescription = "", 
headerLink = "", 
keywords = []) 
{
this.header = header;
this.description = description;
this.startDate = startDate;
this.endDate = endDate;
this.headerIcon = headerIcon;
this.headerDescription = headerDescription;
this.headerLink = headerLink;
this.keywords = keywords;
}
}

有办法吗?

感谢您的宝贵时间。

可能是这样的:

const defaultProps = ()=> new Experience("Experience", "")
class ExperienceForm extends React.Component {
constructor(props) {
super(props);
this.experience = this.props.experience || defaultProps() ;
}

更简洁的方式是:

class ExperienceForm extends React.Component {
constructor(props) {
super(props);
this.experience = this.props.experience || new Experience("Experience","");
}

最新更新