如何为函数设置 defaultProps?

IT技术 reactjs
2021-05-19 04:39:57

是否可以为函数设置 defaultProps?下面的代码不起作用。它不喜欢“这个”。我试过 1_ bind defaultProps 到 'this',或者 2_ bind handleClose 到 'this',都没有效果。我使用 ES6 类。

SaveDialog.propTypes = {
  note: React.PropTypes.string,
  onCancel: React.PropTypes.func,
  onSave: React.PropTypes.func,
  onEditChange: React.PropTypes.func
};

SaveDialog.defaultProps = {
  note: '',
  onCancel: {this.handleClose},
  onSave: {this.handleClose},
  onEditChange: {this.handleChange}
};
3个回答

propTypes是一个验证器。我们使用 propTypes 来记录传递给组件的预期属性类型。React 根据这些定义检查传递给组件的 props,当它们不匹配时将导致警告/错误。

我们可以使用defaultProps属性为 props 定义默认值defaultProps 用于确保 props 将具有一个值,如果它不是由父组件指定的。propTypes 类型检查发生在解析 defaultProps 之后,因此类型检查也将应用于 defaultProps。

这里我们有

SaveDialog.propTypes {
  note: PropTypes.string,
  onCancel: PropTypes.func,
  onSave: PropTypes.func,
  onEditChange: PropTypes.func,
};

REACT为确保该noteprops是一个字符串,并确保制作onSaveonCancelonEditChangeprops的功能。否则,将导致警告/错误。

这里我们有

SaveDialog.defaultProps {
  note: '',
  onCancel: {this.handleClose},
  onSave: {this.handleClose},
  onEditChange: {this.handleChange},
};

在 SaveDialog.propTypes 中,note已声明为字符串。让我们假设父容器尚未指定 prop。由于 note 没有值,我们将使用 defaultProps 中提供的默认值。note 的默认值为空字符串。当类型检查发生时,我们看到 prop 是一个字符串,实际上是一个空字符串。这里没有问题,让我们继续。

接下来,onCancel在 SaveDialog.PropTypes {...}; onCancel 已被声明为 func(函数)。假设父容器没有指定 prop,我们将使用 defaultProps 中 onCancel 的默认值。默认值为this.handleClose

让我们来谈谈这里发生了什么。简单来说,this就是指调用函数的对象。

在这种情况下,defaultProps无法访问该onCancel函数,并且因为 onCancel 未在 中定义defaultProps,所以它返回undefined或错误/警告。

如果是这样,我们所要做的就是定义我们想要onCanceldefaultProps.

所以我们可以在 defaultProps 中声明函数,或者我们可以让默认值是一个空函数,明确说明 onCancel、onSave 或 onEditChange 函数是返回 undefined 的空函数。

SaveDialog.defaultProps {
  note: '',
  onCancel: () => {},
  onSave: () => {},
  onEditChange: () => {},
};

或者

SaveDialog.defaultProps {
  note: '',
  onCancel: () => {
        // handleClose function here
  },
  onSave: () => {
    // handleClose function here
  },
  onEditChange: () => {
    // handleChange function here
  },
};

您可以使用 getDefaultProps 方法。

getDefaultProps() {
  return {
    note: '',
    onCancel: this.handleClose.this(bind),
    onSave: this.handleClose.this(bind),
    onEditChange: this.handleChange.this(bind)
  };
}

设置组件的默认 props 并将函数附加到构造函数中的组件。

constructor() {
  super();
  this.extFunction = extFunction.bind(this);
 }