React-JS: accessing a child method through a HOC wrapper

I have an Editor component that looks like this:

 class EditorComp extends Component { focus() { this.refs.input.focus(); } render() { return ( <input ref="input" ... /> ); } } 

Thus, elements that use EditorComp can set ref and call its focus method and apply focus to the lower-level input, for example:

 class Parent extends Component { render() { return ( <div> <button onClick={() => this.refs.editor.focus()}>Focus</button> <EditorComp ref="editor" /> </div> ); } } 

However, when wrapping EditorComp in a higher-order component (for example, react-redux connect() ), EditorComp loses the focus method because it falls under the HOC.

Example:

 const WrappedEditor = connect()(EditorComp); // react-redux connect, for example const wrappedEditorInstance = <WrappedEditor />; wrappedEditorInstance.focus() // Error! Focus is not a function. 

Is there a way to pass a method or component references through the parent HOCs of the child component?


Edit: Or is there a converse solution in which the parent passes a function that sets the focus command? I examined the use of event-emitter , and when the child listens for the focus event focus by the parent, however this seems cumbersome and unnecessary.

+5
source share
1 answer

1 instance of return return

 class EditorComp extends Component { focus() { this.refs.input.focus(); } componentDidMount(){ this.props.onMount(this) } render() { return ( <input ref="input" ... /> ); } } export default connect(state=>({state}), actions)(EditorComp); class Parent extends Component { render() { return ( <div> <button onClick={() => this.editor.focus()}>Focus</button> <EditorComp onMount={c=>this.editor=c} ref="editor" /> </div> ); } } 

2 way position

 class EditorComp extends Component { componentDidUpdate(prevProps, prevState){ let {input}= this.refs this.props.isFocus? input.focus():input.blur(); } render() { return ( <input ref="input" ... /> ); } } export default connect(state=>({state}), actions)(EditorComp); class Parent extends Component { render() { return ( <div> <button onClick={() => this.setState({isfocus:true});}>Focus</button> <EditorComp isFocus={this.state.isfocus} ref="editor" /> </div> ); } } 
+6
source

All Articles