react 如何继承
在React中,组件继承并非推荐的设计模式(官方更推崇组合优于继承),但技术上仍可通过以下方式实现类似效果:

使用ES6类继承
通过extends关键字继承父组件类,子组件可访问父组件的生命周期方法、state和props:

class ParentComponent extends React.Component {
sharedMethod() {
console.log('This method is inherited');
}
}
class ChildComponent extends ParentComponent {
render() {
this.sharedMethod(); // 调用继承的方法
return <div>Child Component</div>;
}
}
高阶组件(HOC)模式
通过函数包装组件实现逻辑复用,这是React更推荐的模式:
function withLogger(WrappedComponent) {
return class extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
const EnhancedComponent = withLogger(MyComponent);
组合模式
通过props传递组件或数据实现功能复用:
function Parent({ children }) {
return <div className="parent">{children}</div>;
}
function App() {
return (
<Parent>
<ChildComponent />
</Parent>
);
}
注意事项
- 继承可能导致组件间紧密耦合
- React官方文档明确建议使用组合而非继承
- 生命周期方法覆盖需通过
super调用父类方法 - Context API或自定义Hook通常是更好的复用方案






