我有一個table列表,其中每一行都有一個menu按鈕,為此我需要一個ref. 我在我的項目中使用 react mui,它是menu。我試過像這樣創(chuàng)建參考:const {rows} = props;const refs = Array.from({length: rows.length}, a => React.useRef<HTMLButtonElement>(null));然后嘗試map在每個函數(shù)上使用像這樣的內(nèi)部函數(shù)button:<Button ref={refs[index]} aria-controls="menu-list-grow" aria-haspopup="true" onClick={() => handleToggle(row.id)}>Velg</Button> <Popper open={!!checkIfOpen(row.id)} anchorEl={refs[index].current} keepMounted transition disablePortal> {({TransitionProps, placement}) => ( <Grow {...TransitionProps} style={{transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom'}}> <Paper id="menu-list-grow"> <ClickAwayListener onClickAway={(e) => handleClose(e, refs[index].current)}> <MenuList> <MenuItem onClick={(e) => handleClose(e, refs[index].current)}>Profile</MenuItem> <MenuItem onClick={(e) => handleClose(e, refs[index].current)}>My account</MenuItem> <MenuItem onClick={(e) => handleClose(e, refs[index].current)}>Logout</MenuItem> </MenuList> </ClickAwayListener> </Paper> </Grow> )}</Popper>但是,然后我收到一個錯誤:React Hook "React.useRef" 不能在回調(diào)中調(diào)用。React Hooks 必須在 React 函數(shù)組件或自定義 React Hook 函數(shù)中調(diào)用 react-hooks/rules-of-hooks我怎樣才能動態(tài)地做到這一點,以便我可以在 map 函數(shù)中使用 refs。我已經(jīng)嘗試過答案中的建議,但我無法讓它發(fā)揮作用。這是示例的代碼和框。
React 使用 Typescript 創(chuàng)建動態(tài)引用
繁星點點滴滴
2021-10-14 11:04:21