ComponentDidMount 中的 ref 为 null

问题描述

我有一个 KonvaJS 阶段的参考。在ComponentDidMount中,this.stageRef.current的值为null。任何想法为什么?

我的代码如下:

import React,{ useState } from "react"
import { Stage,Layer,Rect,Text } from 'react-konva';
import Konva from 'konva';

class MyComponent extends React.Component {

  constructor() {
    super()
    this.stageRef = React.createRef()
  }

  componentDidMount() {
    // this.stageRef.current is null here!
  }


  render() {
    return (
      <>
          <Stage id="canvas-text"
            width={400} height={163}
            className="stage"
            ref={this.stageRef}>
            <Layer>
              <Text fontFamily='Karla' fontSize={24} align='center' width={400} y={30} text={"Hello"} />
            </Layer>
          </Stage>
      </>
    )
  }
}

export default MyComponent;

解决方法

Stage 组件是一个函数组件,它将引用转发到其底层子组件。 You can inspect the sources

export const Stage = React.forwardRef((props,ref) => {
  return <StageWrap {...props} forwardedRef={ref} />;
});

您提供的一个直接示例表明 the ref references the underlying StageWrap component appropriately