简体   繁体   English

如何从库中扩展React组件

[英]How to extend a react component from a library

I want to extend the FormControl component from react-bootstrap . 我想从react-bootstrap扩展FormControl组件。 Importantly though, I want my extended component to replace the react-bootstrap component, so that importing from the react-bootstrap package actually imports my extended component. 不过重要的是,我希望扩展组件替换 react-bootstrap组件,以便从react-bootstrap包中导入实际上会导入我的扩展组件。

Mostly I need to change the render method to include an absolutely-positioned counter for input[type=text] and textarea nodes, by looking at their inputRef prop. 通常,我需要通过查看它们的inputRef ,将render方法更改为包括用于input[type=text]textarea节点的绝对定位的计数器。

What is the best way to do this? 做这个的最好方式是什么?

Reacts core idea is composability over inheritance . 反应核心思想是可继承性。 So you wrap you component around the bootstrap component and use your component everywhere . 因此,您可以将组件包装在bootstrap组件周围,并在各处使用该组件。

For extending, this should do: 为了扩展,应该这样做:

import MyComponent from 'react-bootstrap'

class NewComponent extends MyComponent {

}

Pretty sure you can't overwrite an import from a package like you want though because it makes no sense to do so. 可以肯定的是,尽管不能这样做,但是绝对不能覆盖所需包中的导入内容。 Just import from the new component instead. 只需从新组件导入即可。

Why exactly do you want to overwrite the existing instead of just providing a wrapping component that inherits it? 您为什么要覆盖现有的内容,而不是仅仅提供一个继承它的包装组件,为什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM