gpt4 book ai didi

inheritance - 如何在 React 组件和 es6 类中使用继承

转载 作者:行者123 更新时间:2023-12-03 13:37:20 25 4
gpt4 key购买 nike

我正在尝试对 React 组件进行子类化,但我的重写方法没有被调用:

class Foo extends React.Component {
someMethod() { ... }

render() {
return <div>{this.someMethod()}</div>;
}
}

class Bar extends Foo {
someMethod() {
// Never gets called
}
}

事实上,当我渲染 <Bar /> 时在我的 DOM 中并查看调试器中的组件,它显示组件类型为“Foo”。

(另外,请注意,我熟悉有关组合与继承的所有争论。相信我,继承确实是我的特定用例的正确答案,所以我们不要开始这个争论。)

(另外,我知道潜在的重复问题 #27233491 ,但那里给出的解决方案实际上似乎并不适合我。)

更新:

我在 CodePen 上看到 @Aaron 的示例,展示了其工作原理,但我在我的应用程序中看到了不同的行为。具体来说:

class Foo extends React.Component {
render() {
console.log(this); // Always prints 'Foo...'.
return <div></div>
}
}

class Bar extends Foo {
render() {
console.log(this); // Always prints 'Bar...'.
return super.render();
}
}

当我渲染 Bar 时,我在开发控制台上看到的是:

> Bar { props: ...etc. }
> Foo { props: ...etc. }

换句话说,第一个日志语句将“this”打印为 Bar 类型,第二个日志语句将“this”打印为 Foo 类型。两者都来自同一个 render() 调用。

最佳答案

发现问题:我在基类上使用 withRouter() 。您不能从 HoC 继承,它会将所有方法视为已调用了 .bind(this)。

关于inheritance - 如何在 React 组件和 es6 类中使用继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37282201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com