我试图让img元素打印在控制台上,但出于某种原因,我得到的唯一东西是未定义的和空的。这是我的密码:
import CardContent from '@mui/material/CardContent';
import CardActions from '@mui/material/CardActions';
import UIButton from 'app/main/components/UIButton';
import { useRef, useEffect } from 'react';
function ExpandImageDialog({ open, onClose: close, url }) {
const refInput = useRef();
const styleImage = () => {
console.log(refInput.current, 'it got here');
};
useEffect(() => {
styleImage();
}, [open]);
return (
<Modal open={open} onClose={close}>
<Card className="px-20 pt-6 pb-32" sx={modalStyle}>
<CardHeader title="Visualização de imagem" />
<hr />
<CardContent>
<img
className="flex-img"
loading="lazy"
src={url}
alt="Documento"
style={imageStyle}
ref={refInput} />
</CardContent>
<CardActions className="justify-end">
<UIButton onClick={close}>Voltar</UIButton>
</CardActions>
</Card>
</Modal>
);
}如果我做了明显的错事,我就会对此感到抱歉。
谢谢你的帮助!
发布于 2022-03-15 01:02:55
您使用参考文献的方式是正确的,请参阅这个复制用于一个简单的复制。以下是代码:
import React from 'react';
import { render } from 'react-dom';
let renderCount = 0;
const App = () => {
const [isVisible, setIsVisible] = React.useState(false);
const imgRef = React.useRef();
const styleImage = () => {
console.log('img ref = ', imgRef.current);
};
const handleClick = () => {
setIsVisible(!isVisible);
};
React.useEffect(() => {
styleImage();
}, [isVisible]);
renderCount += 1;
return (
<div>
<div>render count = {renderCount}</div>
<button onClick={handleClick}>{isVisible ? 'Hide' : 'Show'} image</button>
<br />
<CustomImg isVisible={isVisible}>
<img src="https://picsum.photos/200/300" ref={imgRef} />
</CustomImg>
<br />
</div>
);
};
// Same as your Modal component
const CustomImg = ({ isVisible, children }) => {
if (!isVisible) return <></>; // Component returns nothing, so img isn't known. Therefore, ref is undefined on the first render.
return <div>{children}</div>;
};
render(<App />, document.getElementById('root'));问题来自您传递给open/close组件的支柱Modal。如果没有呈现,那么您的引用将保持未定义。null状态肯定来自您的模式以及。在我的示例中,尝试显示然后隐藏图像,在隐藏它之后,您将看到ref是空的,这是正常的。有一个重新呈现,所以裁判也被重置。
注意,我在组件之外创建了变量renderCount,因此它是一个全局变量,您可以使用它来检查组件重新呈现的次数。试着去做看看会发生什么。
发布于 2022-03-15 01:27:56
你的代码看起来是正确的。
它是空的,因为您在useEffect中记录ref并依赖于open。这将在安装组件时运行。
如果您使用refInput作为依赖项尝试下面的操作,您应该会看到ref日志。
useEffect(()=>{
console.log(refInput.current, 'it got here');
}, [refInput])https://stackoverflow.com/questions/71475611
复制相似问题