My component uses a function to render some inner text. I'd like to allow the owner of my component to provide a custom function as a property. If no custom property is provided, the component will use it's own default function. So naturally, I turned to getDefaultProps
like so:
propTypes: function() {
renderText: React.PropTypes.func
};
getDefaultProps: function() {
return {
renderText: this._renderText
};
}
The problem is that _renderText
is undefined
when getDefaultProps
is called. I can get around this by checking if this.props.renderText
is defined and falling back to this._renderText
if needed. But his doesn't feel like the React way of doing things.
It would work if you defined renderText
function:
getDefaultProps: function() {
return {
renderText: function() {
// do sth
}
};
}
I don't think you can use this
like you've tried, because:
getDefaultProps
This method is invoked before any instances are created and thus cannot rely on
this.prop
Source: https://facebook.github.io/react/docs/component-specs.html#getdefaultprops
You can use this:
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
}
this solution works fine in react-router even no Redux or Flux and so on.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.