【问题标题】:Overriding parent component method in ReactJS在 ReactJS 中覆盖父组件方法
【发布时间】:2018-12-20 15:45:48
【问题描述】:

我有一个扩展自定义组件的类,该组件扩展了另一个自定义组件。我想覆盖handleReload() 函数来添加一些额外的功能。我不想完全改变它的行为。问题是即使在页面加载时我也会收到错误,并且它缺少任何功能。

稍微总结一下,有3层组件,parent -> child -> grandchild,handleReload()在child中声明。

export default class Child extends Parent {

  handleReload() {
    return () => {
      const { name, load } = this.props
      load(name)
    }
  }

  <ReloadButton
    value={'action.reload'}
    onClick={::this.handleReload()}
    privilege={`${metaForm(name)}:Read`}
  />

}

现在我想做的是这样的:

export class GrandChild extends Child {

  handleReload() {
    super.handleReload()
    // something else here
 }
}

【问题讨论】:

  • 我认为您的设计有点“过于复杂”。组件之间的继承,即使在反应中完全可能,也是一个非常备用的情况。他们在文档中说,到目前为止,在他们对 react 的所有使用中,他们从来没有遇到过需要在组件之间使用继承的情况。
  • 无法更改设计。有什么可能的方法可以覆盖该方法吗?
  • 给定您的代码,尝试在 GrandChild 类的构造函数中添加以下内容:this.handleReload = this.handleReload.bind(this);
  • 已经试过了,没成功。

标签: javascript reactjs


【解决方案1】:

您需要评估 handleReload 中的某些内容以判断它是否来自孙子,然后使用某种 if 语句来执行 thisthat .

// ----- parent.js
export class ParentContainer extends Component {

    import {GrandChild} from './components/grandchild';

    handleReload = type => {
      if(type === 'grandchild'){
        // something
      } else {
        // something else
      }
    }

    render() {
      return (
            <GrandChild onReload={this.handleReload} /> 
      )
    }
  }

在 props 中传回的示例

// /  ----- /components/grandchild.js 
export class GrandChild extends Component {

    render() {
      return (
            <button onClick={this.props.onReload('grandchild')}
      );
    }
 }

【讨论】:

  • 这似乎有点过头了。我无法更改父母的代码。
  • 如果您不评估某些内容或将其传递给为孙子构建的单独函数,您不能期望父函数根据其子函数执行不同的操作。
  • 然后我应该找到另一个逻辑来提供我需要的功能。感谢您的帮助,不胜感激。
猜你喜欢
  • 1970-01-01
  • 2018-10-05
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2015-03-29
  • 2011-04-17
  • 1970-01-01
相关资源
最近更新 更多