NISHIO Hirokazu[Translate]
Function components cannot be given refs
>Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Material-UIのMenuが子要素にrefをインジェクトしようとして、それが関数コンポーネントの時に警告される。
ts
<Menu ... > <MyMenuItem onClick={exportForRegroup}>Export for Regroup</MyMenuItem>

ts
const MyMenuItem = (props: any) => { const { children, onClick, ...other } = props; const f = () => { onClick(); setAnchorEl(null); }; return ( <MenuItem onClick={f} {...other}> {children} </MenuItem> ); };

修正
警告メッセージのとおりReact.forwardRefでrefを転送する
ts
const MyMenuItem = React.forwardRef((props: any, ref) => { // here ... return ( <MenuItem onClick={f} {...other} ref={ref}> // here {children} </MenuItem> ); });


"Engineer's way of creating knowledge" the English version of my book is now available on [Engineer's way of creating knowledge]

(C)NISHIO Hirokazu / Converted from [Scrapbox] at [Edit]