[英]Passing refs in React
In my App
component, I have 2 components Navbar
and View
.在我的
App
组件中,我有 2 个组件Navbar
和View
。 In my Navbar
component, I have an ExportButton
component which onClick should generate a screenshot of the View
component by passing its ref.在我的
Navbar
组件中,我有一个ExportButton
组件,onClick 应该通过传递其 ref 来生成View
组件的屏幕截图。
App.js应用程序.js
function App() {
const view = useRef();
return (
<div className="App">
<Navbar takeSnap={view}/>
<View ref={view}/>
</div>
);
}
Navbar.js导航栏.js
const Navbar = ({ takeSnap }) => {
return (
<>
<Lists />
<ExportButton takeSnap={takeSnap} />
</>
);
};
Button.js按钮.js
const ExportButton = ({ takeSnap }) => {
function handleClick(takeSnap) {
domtoimage.toBlob(takeSnap.current, {}).then(function (blob) {
saveAs(blob, "myImage.png");
});
}
return (
<Button onClick={() => handleClick(takeSnap)} />
);
};
I having some trouble passing ref of View
to use the library dom-to-image to take a screenshot.我在传递
View
的引用以使用库 dom-to-image 截屏时遇到了一些麻烦。 The error says "Uncaught (in promise) TypeError: Cannot read property 'cloneNode' of undefined at makeNodeCopy".错误显示“未捕获(承诺中)类型错误:无法读取 makeNodeCopy 处未定义的属性 'cloneNode'”。 This might be a quick fix but I'm not sure where I'm going wrong.
这可能是一个快速修复,但我不确定我哪里出错了。
You cannot create a ref
for a component, a ref
can only reference a DOM element.您不能为组件创建
ref
, ref
只能引用 DOM 元素。 When you do:当你这样做时:
<View ref={view}/>
ref
is a reserved keyword and it won't be passed down to your View render function. ref
是一个保留关键字,它不会传递给您的视图渲染 function。
You can use forwardRef
to solve this problem, or simply use a different keyword such as myRef:您可以使用
forwardRef
来解决这个问题,或者简单地使用不同的关键字,例如 myRef:
<View myRef={view}/>
Then when you render your View
, you can assign this ref to the element you want the screenshot from:然后,当您渲染
View
时,您可以将此 ref 分配给您想要截屏的元素:
<div ref={myRef} ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.