React.js:如何定义默认属性函数

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

本文关键字:定义 默认 属性 函数 js 何定义 React      更新时间:2023-09-26

我的组件使用一个函数来呈现一些内部文本。我想允许我的组件的所有者提供自定义函数作为属性。如果没有提供自定义属性,组件将使用它自己的默认函数。因此,我很自然地转向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.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
}

这个解决方案在react-router中工作得很好,即使没有Redux或Flux等