【问题标题】:React + ES6: defaultProps of hierarchyReact + ES6:层次结构的默认属性
【发布时间】:2015-10-30 09:56:24
【问题描述】:

由于我将代码重构为 ES6,因此我将所有默认值移至 SomeClass.defaultProps = { ... }

假设一种情况,当有一个类层次结构时,我需要为整个层次结构保留一些默认值。但问题defaultProps 不适用于扩展类:

class AbstractComponent extends React.Component {
  constructor(props) { super(props) }
}
class OneOfImplementations extends AbstractComponent {
  constructor(props) { super(props) }
}
//Problem: hierarchy defaults doesn't work
AbstractComponent.defaultProps = { name: 'Super' } 

Fiddle example

P.S. 我想知道为整个层次结构保留公共资源(变量/函数)的最佳位置在哪里?也许在AbstractComponent 做这样的事情:

constructor(props) {
  super(_.assign(props, {
    commonValue: 128,
    commonCallback: _.noop
  }));
}

但问题是无法覆盖子类中的属性之一

【问题讨论】:

  • 我很确定 react 建议实际上避免这种对自己的类的扩展
  • @Joshua 请解释一下你的意思。哪种扩展?
  • 这一点 class OneOfImplementations extends AbstractComponent { 我很确定我看到辣条说应该避免,即一切都应该扩展 React.Component
  • 我正在寻找它,但找不到github问题
  • 什么是 ES6 语法不支持 mixins,抽象功能有点未知,但看起来 @decorator 语法可能是首选 - github.com/facebook/react/issues/5010

标签: javascript reactjs ecmascript-6


【解决方案1】:

或者,如果您在 Babel 中使用 stage: 0 stage: 2 预设(或直接使用 transform),您可以使用 es7 建议的静态属性:

class AbstractComponent extends React.PureComponent {

  static defaultProps = { name: 'Super' }

  // Bonus: you can also set instance properties like this
  state = {
    someState: true,
  }

  // ^ Combined with new arrow binding syntax, you often don't need
  // to override the constructor (for state or .bind(this) reasons)
  onKeyPress = () => {
    // ...
  }
}

【讨论】:

  • 很遗憾我没有 es7 支持
【解决方案2】:

“defaultProps”属性的声明顺序似乎很重要:

class AbstractComponent extends React.Component {
  constructor(props) { super(props) }

  render() {
    return <div>Prop: [ {this.props.name} ]</div>
  }
}
AbstractComponent.defaultProps = { name: 'Super' }

class ComponentImpl1 extends AbstractComponent {
  constructor(props) { super(props) }
}

// works

http://jsfiddle.net/jwm6k66c/103/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2020-09-30
相关资源
最近更新 更多