Reactで子コンポーネントの関数を親コンポーネント内で実行したい。
・子コンポーネントでshowAlertを定義
・親コンポーネントの特定buttonに紐付けたイベント内でshowAlertを実行
前提
refとforwardRef 、 useImperativeHandleを使用して実装を試みましたが、下記のエラーが出てしまいます。
showAlert関数は、実際のコードでは子コンポーネント内フォームに入力された値を使用する計算関数です。
発生している問題・エラーメッセージ
Uncaught TypeError: Cannot read properties of null (reading 'showAlert')
該当のソースコード
React.js
1import React, { useImperativeHandle, forwardRef, useRef } from "react"; 2 3const childComponent = forwardRef((ref) => { 4const handleShow = () => { 5 showAlert() 6}; 7 8 useImperativeHandle( 9 ref, 10 () => ({ 11 showAlert() { 12 alert("hoge") 13 } 14 }), 15 ) 16retrun( 17<Button 18 className="btn btn-primary px-3" 19 onClick={handleShow} 20 > 21 </Button> 22) 23}); 24 25 26const parentComponent = () => { 27const childFunc = useRef(null); 28const handleClick= () => { 29childFunc.current.calculate(); 30} 31return( 32<MyChildComponent 33 ref={childRef} 34/> 35 <Button 36 onClick={handleClick} 37 > 38 </Button> 39) 40}; 41export default parentComponent;
試したこと
const childFunc = useRef(null); ↓ const childFunc = useRef();
などを試しましたが、undefinedに変わるだけでした。
回答1件
あなたの回答
tips
プレビュー