微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ComponentDidMount 中的 ref 为 null

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。