React + ES6:defaultProps of hierarchy

VB_*_*VB_ 3 javascript ecmascript-6 reactjs

由于我将我的代码重构为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' } 
Run Code Online (Sandbox Code Playgroud)

小提琴的例子

PS我想知道整个层次结构中保存公共(变量/函数)的最佳位置在哪里?也许做这样的事情AbstractComponent:

constructor(props) {
  super(_.assign(props, {
    commonValue: 128,
    commonCallback: _.noop
  }));
}
Run Code Online (Sandbox Code Playgroud)

但问题是,从子类中覆盖其中一个属性变得不可能

Dom*_*nic 6

或者,如果您正在使用舞台:0 stage: 2预设Babel(或直接变换),您可以使用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 = () => {
    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)


May*_*yas 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
Run Code Online (Sandbox Code Playgroud)

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