【发布时间】:2021-05-22 09:03:20
【问题描述】:
我正在尝试在 React 打字稿中创建一个网格,想要访问每个节点内带有 refs 的节点我正在使用 useImperativeHandle 返回一个函数和节点状态
const Grid: React.FC<PropsType> = (props) => {
const makeGrid = (): void => {
const newGrid: gridNode[][] = []
for (let i = 0; i < HIEGHT; i++) {
const gridRow: gridNode[] = []
for (let j = 0; j < WIDTH; j++) {
const node: gridNode = {
row: i,
col: j,
ref: React.createRef<NodeHandle>()
}
gridRow.push(node)
}
newGrid.push(gridRow)
}
setGrid(newGrid)
}
useEffect(() => { makeGrid() }, [])
return (
<>
{grid.forEach(row => {
return (<>
{row.forEach(node => {
<Node ref = {node.ref} />
})
</>)
})
</>
)
}
我想使用 useRef() 钩子使其更内联我正在使用的功能组件,我不知道将 refs 放在状态对象中是否是最佳做法
const Node: React.ForwardRefRenderFunction<NodeHandle, NodeProps> = (props, ref) => {
changeStatus = (newStatus: string) => {
//changes the status
}
useImperativeHandle(ref, () => {
return {
changeStatus,
status,
}
})
return (
<div>Node</div>
)
}
我对 typeScript 很陌生,以前也没有使用过这么多的 refs
【问题讨论】:
标签: reactjs typescript react-hooks react-ref