react 如何继承
在React中,组件继承并不是推荐的设计模式,因为React更倾向于组合(composition)而非继承。但若需要实现类似继承的功能,可以通过以下方式模拟:

使用高阶组件(HOC)
高阶组件是一种将组件作为参数并返回新组件的函数,可用于共享逻辑:

function withBaseLogic(WrappedComponent) {
return class extends React.Component {
baseMethod() {
console.log('共享方法');
}
render() {
return <WrappedComponent {...this.props} baseMethod={this.baseMethod} />;
}
};
}
class ChildComponent extends React.Component {
render() {
this.props.baseMethod();
return <div>子组件</div>;
}
}
export default withBaseLogic(ChildComponent);
使用自定义Hook
React 16.8+版本可通过Hook共享状态逻辑:
function useBaseLogic() {
const baseMethod = () => {
console.log('共享逻辑');
};
return { baseMethod };
}
function ChildComponent() {
const { baseMethod } = useBaseLogic();
baseMethod();
return <div>子组件</div>;
}
组合模式
通过props.children或特定prop实现组件嵌套:
function BaseComponent({ children }) {
const baseMethod = () => {
console.log('基础功能');
};
return children({ baseMethod });
}
function App() {
return (
<BaseComponent>
{({ baseMethod }) => {
baseMethod();
return <div>子组件内容</div>;
}}
</BaseComponent>
);
}
注意事项
- React官方文档明确建议避免继承层次结构
- 共享UI可使用组合,共享状态逻辑推荐使用Hooks或HOC
- 类组件的extends仅适用于极少需要扩展React内置组件的情况
以上模式均能实现代码复用,但组合模式通常更符合React的设计哲学。






