在React中,当继承propTypes时,如何避免重复? [英] In React, when inheriting propTypes, how do I avoid duplication?

查看:251
本文介绍了在React中,当继承propTypes时,如何避免重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一些共享方法和一些(但不是全部)道具的React组件使用一个抽象超类.

I'm using an abstract superclass for some React components that share methods and some (but not all) props.

class AbstractStory extends Component { ... }
AbstractStory.propTypes = {
  storyForm: PropTypes.string,
  timestamp: PropTypes.number
}

class NewContentStory extends AbstractStory { ... }

我假设,如果子类的propType与超类没有区别,则可以在子类上不声明它们,而它们将从超类继承.

I'm assuming that if the propTypes of the subclass don't differ from the superclass, I can leave them undeclared on the subclass, and they will be inherited from the superclass.

但是,如果子类还有其他属性,有没有一种好的方法可以在不重述超类上声明的内容的情况下声明它们?这样有什么问题吗?

But, if there are additional properties of the subclass, is there a good way to declare them without restating what is declared on the superclass? Is there any issues doing it like this?

NewContentStory.propType = {... AbstractStory, newProp: PropTypes.string}

如果子类修改了在超类上声明的属性(使其成为必需的,为对象添加形状等),该怎么办?

What about if the subclass modifies a property declared on the superclass (making it required, adding shape to an object, etc.)?

推荐答案

真正的答案是,按照惯例,您实际上不想扩展React.Component以外的组件,因为功能组合是React中抽象的主要方式.

The real answer is that by convention you don't really want to extend components other than React.Component as functional composition is the primary way of abstraction in React.

换句话说:您应该嵌套组件,而不是在React中扩展类.

In other words: You should nest components, rather than extending classes in React.

这篇关于在React中,当继承propTypes时,如何避免重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆