React + ES6:defaultProps of hierarchy

时间:2015-10-30 09:56:24

标签: javascript reactjs ecmascript-6

由于我将代码重构为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
  }));
}

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

2 个答案:

答案 0 :(得分:6)

或者如果您使用阶段:0 stage: 2预设Babel(或直接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 = () => {
    // ...
  }
}

答案 1 :(得分:5)

似乎“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/