在正方形中反应 Konva 中心文本

React Konva center text in square

我正在尝试使用 RectText 组件创建一个带有一些文本居中的按钮。

这是一段代码:

        <Stage>
            <Layer>
                <Rect
                    x={window.innerWidth - 50}
                    y={window.innerHeight - 50}
                    width={30}
                    height={30}
                    fill='#f2f1f0'
                    stroke='#777'
                    strokeWidth={1}
                >
                <Text
                  fontSize={20}
                  text="+"
                  stroke='#777'
                  strokeWidth={1}
                  align="center"
                />
               <Rect />
            </Layer>
        </Stage>

但是我得到了这个错误:

Uncaught (in promise) TypeError: parentInstance.add is not a function

是否有将 Text 组件放入 Rect 组件的正确方法?

试试这个:

const App = () => {
  const textRef = React.useRef();
  const [size, setSize] = React.useState({ x: 0, y: 0 });
  React.useEffect(() => {
    setSize({
      width: textRef.current.width(),
      height: textRef.current.height()
    });
  }, []);
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Group x={20} y={50}>
          <Rect
              x={window.innerWidth - 50}
              y={window.innerHeight - 50}
              width={size.width}
              height={size.height}
              fill='#f2f1f0'
              stroke='#777'
              strokeWidth={1}
          />
          <Text
            ref={textRef}
            fontSize={20}
            text="+"
            stroke='#777'
            strokeWidth={1}
            align="center"
          />
        </Group>
      </Layer>
    </Stage>
  );
};