A simple component may have public methods that are accessible if it's a ref somewhere. I usually use if for focus, scrollToBottom etc.
class ArticleSearch extends Component {
render() { return <div><input type="text" ref="input" /></div> }
focus() { this.refs.input.focus() }
}
// some other component:
render() { return <div>...<ArticleSearch ref="articleSearch" />...</div> }
doSomething() {
this.refs.articleSearch.focus()
}
In case component is @connected, the methods aren't accessible anymore.
I can use withRef: true and this.refs.articleSearch.getWrappedInstance().focus() but that wouldn't be clean, as I explicitly specify the getWrappedInstance(). If I remove the @connect code will break.
Would it make sense to copy some selective methods from wrapped component into the Connect component?
Something like (https://github.com/rackt/react-redux/blob/master/src%2Fcomponents%2Fconnect.js) :
function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
// ...
return function wrapWithConnect(WrappedComponent) {
class Connect extends Component {
// ...
constructor(props, context) {
//...
if (options.copyMethods) {
invariant(options.withRef, 'copyMethods requires the withRef option to be true')
options.copyMethods.forEach(m => this[m] = (...args) { return this.wrappedInstance[m](...args) })
}
}
Usage:
@connect(null, null, null, { withRef: true, copyMethods: ['focus', 'scrollToBottom'])
class ArticleSearch extends Component {
//...
focus() { ... }
scrollToBottom() { ... }
}
I'll make a PR if it seems fine.
Update
I see all static methods are copied with hoistStatics, but prototype methods are left out. Solution can be something similar that also copies all prototype methods and binds them to the ref.
As described in https://github.com/rackt/react-redux/pull/270#issuecomment-175217424, it's best to pass callback refs as props for that rather than expose instance methods.
Most helpful comment
As described in https://github.com/rackt/react-redux/pull/270#issuecomment-175217424, it's best to pass callback refs as props for that rather than expose instance methods.