【问题标题】:ref is null in ComponentDidMountref 在 ComponentDidMount 中为空
【发布时间】:2021-08-01 11:02:34
【问题描述】:

我有一个 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;

【问题讨论】:

    标签: reactjs react-native react-component konvajs konvajs-reactjs


    【解决方案1】:

    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

    【讨论】:

    • 这如何回答 OP 的问题?
    • 它解释了它应该如何工作并添加了一个实时工作示例。
    • 我不太关注。您在 Codesandbox 中输入的代码似乎与 OP 完全相同(尽管有格式)。
    • @tmarwen 是对的。对于这个问题,我(过度)简化了我的代码并无意中删除了我自己的错误!
    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2019-08-13
    • 2017-10-24
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多