实际上,在他们的官方文档中,React 的创建者建议使用组合而不是继承:
https://facebook.github.io/react/docs/composition-vs-inheritance.html
我也听说过一些开发者在项目中途一开始选择使用继承的时候转道的案例,正如 React 的人所说,你可能会重新考虑一下:
在 Facebook,我们在数以千计的组件中使用 React,但我们还没有
找到我们建议创建组件的任何用例
继承层次结构。
(...在这里找到):
https://facebook.github.io/react/docs/composition-vs-inheritance.html#so-what-about-inheritance
=========
添加了成分示例:
但是,我下面的组合模式示例可能会帮助您实现您想要的(类似于“类继承”):
Foo.js(只需添加getDefaultProperty())
/* @flow */
import React from 'react';
class Foo extends React.Component {
props : {
prop1 : string
}
static defaultProps = {
prop1: "Default Foo"
}
getDefaultProperty = () => {
return this.prop1;
}
render() {
return;
}
}
export default Foo;
Bar.js(这个部分扩展“Foo”使用composition模式):
/* @flow */
import React from 'react';
import Foo from './Foo.js';
class Bar extends React.Component {
props : {
prop2 : string
}
static defaultProps = {
prop1: "Default Bar",
prop2: "Hello World"
}
componentDidMount() {
console.log(this.refs.parent.getDefaultProperty());
// here you should see prop1 of Foo (the parent) is logged
// or you can copy prop1 value from parent:
if (this.refs.parent && this.refs.parent.getDefaultProperty()){
this.prop1 = this.refs.parent.getDefaultProperty();
}
}
render() {
return (
<Foo ref="parent">
<div>{this.prop2 + ", I am the Bar component, my value now is " + this.prop1}</div>
</Foo>
)
}
}
export default Bar;
更详细地说,Bar 组件仍然扩展了React.Component,但它仍然可以访问Foo 的方法,该方法通过使用ref 返回 Foo 的prop1
其实只要在Bar的render方法中渲染Foo,给它一个ref就可以访问组件Foo的方法了。这是组合模式。