我正在创建一个织物画布和按钮,这些按钮实例化的形状应该是可选择的。我不明白为什么在以下情况下我的组件会被重新渲染两次。因此,我的织物形状无法选择。然而,当我从我的index.tsx文件中移除时,渲染只发生一次,我的形状是可选择的。我可以移除,但我不认为这是最好的解决方案。下面是演示:
const { Fragment, StrictMode, useEffect, useRef } = React;
const { createRoot } = ReactDOM;
const styles = {};
const CanvasComponent = ({ id }) => {
const canvasRef = useRef(null);
useEffect(() => {
console.log('init canvas'); // displayed twice with
canvasRef.current = initCanvas();
}, []);
const initCanvas = () => (
canvasRef.current = new fabric.Canvas(`canvas-${id}`, {
width: 800,
height: 400,
})
);
const addShape = (shapeType: string) => {
let shape: fabric.Object;
switch (shapeType) {
case 'circle':
shape = new fabric.Circle({ radius: 30, fill: 'red', left: 100, top: 100 });
break;
case 'rectangle':
shape = new fabric.Rect({ width: 60, height: 70, fill: 'green', left: 100, top: 100 });
break;
default:
return;
}
canvasRef.current.add(shape);
};
return (
);
}
function StrictModeEnabled() {
return Strict Mode Enabled
;
}
function StrictModeDisabled() {
return Strict Mode Disabled
;
}
const strictModeEnabledRoot = createRoot(document.getElementById("strict-mode-enabled"));
strictModeEnabledRoot.render( );
const strictModeDisabledRoot = createRoot(document.getElementById("strict-mode-disabled"));
strictModeDisabledRoot.render( );
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号