当我使用CSS resize属性调整div容器的大小时,在react中的div容器的高度和宽度我尝试过这个方法,但是我得到错误
import React, { useState, useRef, useEffect } from 'react';
const TextAreaWrapper = () => {
const [dimensions, setDimensions] = useState({ height: 0, width: 0 });
const textareaRef = useRef(null);
useEffect(() => {
const textarea = textareaRef.current;
const handleResize = () => {
console.log('Hello world');
setDimensions({
height: textarea.offsetHeight,
width: textarea.offsetWidth,
});
};
textarea.addEventListener('resize', handleResize);
return () => {
textarea.removeEventListener('resize', handleResize);
};
}, []);
return (
<div>
<textarea ref={textareaRef} />
<p>Height: {dimensions.height}</p>
<p>Width: {dimensions.width}</p>
</div>
);
};
export default TextAreaWrapper;
1条答案
按热度按时间edqdpe6u1#
尝试以下操作(检查ref是否不为空):