前提・実現したいこと
ReactのHOCを使用して、ダイアログ(メッセージボックス)の共通コンポーネントを作成したいです。
ダイアログコンポーネントを作成し、そのコンポーネントをwithBasedComponent.jsでラップして、呼び出し元のコンポーネントでthis.props.xxxの形で使えるようにしたいです。
※他にもスナックバーなどをwithBasedComponent.jsに追加していく予定です
ソースコードは抜粋ですが、実装したところ、ダイアログコンポーネントの指定したメソッドがないとのエラーになりました。
解決方法あるいは上記を実現するにあたり、より良い実装方法があれば、教えていただけないでしょうか?
発生している問題・エラーメッセージ
エラーメッセージ TypeError: _this.msgBoxComponent.current.show is not a function
該当のソースコード
msgbox.js
JSX
1import React, { Component, Fragment } from 'react'; 2import { 3 Dialog, 4 DialogContent, 5 DialogContentText, 6 DialogActions, 7 Button 8 } from '@material-ui/core'; 9 10class MsgBox extends Component { 11 constructor(props) { 12 super(props); 13 this.state = { 14 isOpen: false, 15 callback: null 16 }; 17 }; 18 callbackfunc = () => { 19 this.state.callback(); 20 }; 21 msgBoxClose = () => { 22 this.setState({ isOpen: false }); 23 }; 24 msgBoxSetting = (msgCode, callback) => { 25 // ここでDialogの設定をおこなうコードを書く 26 }; 27 show = (msgCode, callback) => { 28 console.log('msgCode', msgCode) 29 console.log('callback', callback) 30 this.msgBoxSetting(msgCode, callback); 31 }; 32 render() { 33 return ( 34 <Fragment> 35 <Dialog 36 open={this.state.isOpen} 37 onClose={this.msgBoxClose} 38 > 39 test 40 </Dialog> 41 </Fragment> 42 ); 43 } 44} 45 46export default MsgBox;
withBasedComponent.js
JSX
1import React, { Component, Fragment } from 'react'; 2 3import MsgBox from './msgbox'; 4 5export default function withBasedComponent(WrappedComponent) { 6 return class extends Component { 7 constructor(props) { 8 super(props); 9 this.state = { 10 }; 11 this.msgBoxComponent = React.createRef(); 12 13 }; 14 showMessageBox = (msgCode, callback) => { 15 console.log('this.msgBoxComponent.current', this.msgBoxComponent.current) 16 this.msgBoxComponent.current.show(msgCode, callback) // ★showメソッドがなしエラーになる 17 }; 18 render() { 19 const newProps = { 20 showMessageBox: this.showMessageBox 21 }; 22 return ( 23 <Fragment> 24 <MsgBox ref={this.msgBoxComponent} /> 25 <WrappedComponent {...this.props} {...newProps} /> 26 </Fragment> 27 ); 28 } 29 } 30}
呼び出し側の例
import withBasedComponent from './with-based-component'; this.props.showMessageBox('001', null) ※第2引数には、ダイアログでOK押下時に実行させたいメソッドがあれば、指定する(this.xxx() のように) export default withBasedComponent(Login);
補足情報(FW/ツールのバージョンなど)
react: ^16.6.3
react-dom: ^16.6.3
@material-ui/core: ^3.6.2

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。