javascript - 使用 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 期间未定义,我真的不知道是什么导致了这种行为。
如果有人向我解释为什么会发生这种情况,我会很高兴。谢谢你。
解决方案
您正在使用this.shapeRef = React.createRef();
创建参考。
但是在里面setRef
你正在覆盖它:
setRef(ref) {
this.shapeRef = ref;
}
之后这个指挥官this.shapeRef
会参考Konva.Rect
instance。一个实例Konva.Rect
没有current
属性。
所以你有两个选择:
- 只需使用
this.shapeRef
而不是this.shapeRef.current
- 或通过正确设置参考
this.shapeRef.current = ref;
演示:https ://codesandbox.io/s/quirky-firefly-bre9c?file=/src/index.js
推荐阅读
- .htaccess - 将“子文件夹”重定向到新 URL;Joomla 和 .htaccess
- javascript - React Native 后台计时器永不停止
- sql - 将 2 个表合并为 1 个(SQL Server)的最佳方法是什么,只有一个共同的日期时间类型的列
- postgresql - 复制数据或将数据从 CSV 导入 PostgreSQL 时出错
- python - 将列表与 CSV 文件进行比较
- python - Value_counts 未返回所需的输出
- php - 访问部署在共享主机上的公共目录 laravel 5.5
- javascript - Vue:如何在 mapFields 中使用组件道具
- python-3.x - 从 Target 抓取产品和商店信息
- linux-mint - 如何在 Linux Mint 中正确构建 RTEMS 4.11 环境