【发布时间】:2021-04-09 02:00:31
【问题描述】:
[编辑] 已修复(滚动到底部)
您好,我正在尝试为功能组件选择一个反应元素,当前代码:
const Emoji = (props) => {
const copyButton = useRef(null);
function handleHover(e) {
console.log(this.copyButton); //want to select this element
}
function handleMouseOut(e) {
}
return(
<div className="wrapper">
<div id={"emoji-"+props.id} className="emoji" onMouseOver={handleHover} onMouseOut={handleMouseOut}>
<Button ref={copyButton} className="copyButton" buttonText="Copy" buttonColour="primary" />
<Button className="button" buttonText="Information" buttonColour=" " />
<h1>{props.emojiCharacter}</h1>
<p>{props.emojiName}</p>
</div>
</div>
);
}
export default Emoji;
我正在尝试构建一个应用程序,当用户将鼠标悬停在此组件上时,按钮将出现,但是当我尝试选择它们时,我不断收到此错误:TypeError: Cannot read property 'copyButton' of undefined
当我尝试document.getElementById 时,它也会返回 null。
有什么建议吗?谢谢。
已修复
问题是由于该元素是自定义组件而不是默认组件,否则我可以简单地使用copyButton.current
我通过进入组件的 jsx 并将 const Button = (props) => { etc } 声明更改为 a
const Button = React.forwardRef((props, ref) => (
<div ref={ref}
</div>
));
【问题讨论】:
-
这看起来像一个函数组件而不是一个类组件,所以你不会使用
this关键字。你试过console.log(copyButton);吗? -
这看起来像
functional component,所以你不应该做this.copyButton,只是copyButton
标签: javascript reactjs frontend