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