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

标签 javascript reactjs

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

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

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

问题在于,当调用 getDefaultProps 时,_renderText未定义。 我可以通过检查 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

关于javascript - React.js : How to define a default property function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30369598/

相关文章:

javascript - 使用 javascript 或 jquery 从保存的 html 中获取与元素相关的 jquery.data()

javascript - 如何通过代码在迷你图中显示工具提示

javascript - 当状态更新时没有从 redux store 获取更新的状态

javascript - 当 if 语句为 true 时,else 语句仍在运行

javascript - 在 React 组件中获取数据的位置

reactjs - 找不到模块 : Can't resolve 'bootstrap/dist/css/bootstrap.css' in 'C:\Users\test\counter-app\src'

javascript - 混合内容问题 $http.get AngularJS

javascript - AudioBufferSourceNode 连接后才开始播放

javascript - jQuery:预览图像

javascript - Reactjs 和闭包问题