在使用函數組件時,報錯:Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()
解決辦法:
將函數組件通過用forwradRef包裝。
//子組件
function FancyButton(props, ref) (
return <button>Test</button>;
);
export default React.forwardRef(FancyButton);
使用React.useImperativeHandle
可以提供給父組件相應的內部方法進行調用
//子組件
import React, { useImperativeHandle } from "react";
function FancyButton(props, ref) (
useImperativeHandle(ref, () => ({
validate: () => {
},
params: {}
}));
return <button>Test</button>;
);
//父組件
import React, { useCallback, useRef } from "react";
function Parent() {
const formRef = useRef(null);
const onClick = useCallback(()=>{
console.log(formRef.current.params);
formRef.current.validate();
}, []);
return <button onClick={onClick}>父組件</button>
}