首页 > 解决方案 > 使用 render props 访问 refs

问题描述

我正在尝试处理从子组件中提升 ref 的问题。

我的父组件:

import React, { Component, use } from "react";
import { Transformer } from "react-konva";

export default class SelectProvider extends Component {
  constructor(props) {
    super(props);
    this.shapeRef = React.createRef();
    this.trRef = React.createRef();
    this.setRef = this.setRef.bind(this);
  }

  componentDidMount() {
    console.log("mount");
  }

  setRef(ref) {
    this.shapeRef = ref;
  }

  render() {
    return (
      <>
        {this.props.children({
          setRef: this.setRef,
        })}
        <Transformer ref={this.trRef} />
      </>
    );
  }
}

和孩子:

import React from "react";
import { Rect } from "react-konva";
import SelectProvider from "./TransformerProvider";

const RectangleShape = (props) => {
  return (
    <SelectProvider>
      {({ setRef }) => (
        <>
          <Rect ref={setRef} {...props}></Rect>
        </>
      )}
    </SelectProvider>
  );
};

export default RectangleShape;

不幸的shapeRef.current是,我在 componentDidMount 期间未定义,我真的不知道是什么导致了这种行为。

如果有人向我解释为什么会发生这种情况,我会很高兴。谢谢你。

标签: javascriptreactjsreact-konva

解决方案


您正在使用this.shapeRef = React.createRef();创建参考。

但是在里面setRef你正在覆盖它:

setRef(ref) {
  this.shapeRef = ref;
}

之后这个指挥官this.shapeRef会参考Konva.Rectinstance。一个实例Konva.Rect没有current属性。

所以你有两个选择:

  1. 只需使用this.shapeRef而不是this.shapeRef.current
  2. 或通过正确设置参考this.shapeRef.current = ref;

演示:https ://codesandbox.io/s/quirky-firefly-bre9c?file=/src/index.js


推荐阅读