ComponentDidMount 中的 ref 为 null
ref is null in ComponentDidMount
我有一个 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。
我有一个 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。