React.js: 如何定义一个默认的属性函数?

React.js: How to define a default property function?

我的组件使用一个函数来呈现一些内部文本。我想让我的组件的所有者提供自定义函数作为 属性。如果没有提供自定义 属性,组件将使用它自己的默认函数。所以很自然地,我转向 getDefaultProps 像这样:

propTypes: function() {       
  renderText: React.PropTypes.func
};

getDefaultProps: function() {
  return {
    renderText: this._renderText
  };
}

问题是调用getDefaultProps_renderTextundefined。 我可以通过检查是否定义了 this.props.renderText 并在需要时回退到 this._renderText 来解决这个问题。但他的做事方式不像 React。

如果您定义了 renderText 函数,它将起作用:

getDefaultProps: function() {
  return {
    renderText: function() {
      // do sth
    }
  };
}

我认为您不能像您尝试过的那样使用 this,因为:

getDefaultProps

This method is invoked before any instances are created and thus cannot rely on this.prop

来源:https://facebook.github.io/react/docs/component-specs.html#getdefaultprops

你可以使用这个:

Class Test extends Component{
    contrustor(props){
    ...
    }
    notify(data){
        console.log("Yeah!",data);
    }
    return (<div>This is context here.</div>)
}
Test.defaultProps={
    getNotify:Test.prototype.notify
}

即使没有 Redux 或 Flux 等,此解决方案在 react-router 中也能正常工作。