简体   繁体   中英

useRef React Hook

I need to have a reference to a variable so that I can change the value of that variable both in Canvas and ToolsMenu . Therefore I made something similar to this...

function App() {
  const canvas = useRef(); // Value assigned in <Canvas />

  return (
    <>
      <Canvas canvas={canvas} />
      <ToolsMenu canvas={canvas} />
    </>
  );
}

But when I change the canvas.current value in <ToolsMenu /> , the value in <Canvas /> won't get updated. Is there any way I can get something like a C++ pointer in React?

I don't think the useState hook would work because I change the value of canvas through methods ( canvas.getCommandStack().undo() ) and not through setCanvas

function App() {
  const [canvas, setCanvas] = useState(); // Assign in <Canvas />

  return (
    <>
      <Canvas canvas={canvas} setCanvas={setCanvas}/>
      <ToolsMenu canvas={canvas}/>
    </>
  );
}

function Canvas({ canvas, setCanvas }) {
  useEffect(() => {
    setCanvas(new draw2d.Canvas("canvas"));
  }, []);

  // ...

  return <div id="canvas"></div>;
}

function ToolsMenu({ canvas }) {
  const undo = () => canvas?.getCommandStack().undo();
  const redo = () => canvas?.getCommandStack().redo();

  return (
    <>
      <button onClick={undo}>Undo</button>
      <button onClick={redo}>Redo</button>
    </>
  );
}

Or would it still work?

I fixed the problem myself. It has nothing to do with the useRef hook.

I just forgot the , [] in a useEffect hook, inside <Canvas /> , that was initializing canvas.current . So I kept re-initializing the canvas after changing its value.

You can't do this?

function App() {
    const [ref, setRef] = usestate();

    return (
    <>
        <Comp1 value={ref} onChange={setRef(value)}/>
        <Comp2 value={ref} onChange={setRef(value)}/>
    </>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM