我正在尝试建立一个下拉菜单。基本结构Test
是我需要使用Reactref
和来检测内容区域之外的点击的地方styled-components
。
我已经检查了SO中的相关文章,但是它们使用了我的类组件不支持的钩子。
这是代码:
import React from "react";
import PropTypes from "prop-types";
import styled, { ThemeProvider } from "styled-components";
import { theme } from "../theme";
import Icon from "../Icon";
const Container = styled.div`
display: flex;
`};
const SelectorDiv = styled.div`
background-color: black;
color: white;
height: 100px;
`;
class Test extends React.Component {
componentDidMount () {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount () {
document.removeEventListener("mousedown", this.handleClickOutside);
}
handleClickOutside = event => {
console.log(this.refs); // undefined
}
handleClickInside = () => {
alert("Clicked inside");
}
render = () => {
return (
<ThemeProvider theme={theme}>
<Container disabled={disabled}>
<SelectorDiv
onClick={this.handleClickInside}
ref={"wrapper"}
>
<h1>This is the content to click</h1>
</SelectorDiv>
</Container>
</ThemeProvider>
);
};
}
export default Test;
裁判不是工作财产。当点击外面的是我得到undefined
的this.refs
。似乎styled-components
有问题,但是在V4上已解决(我正在使用V5.1.0)。
如何将包装器组件放入我的包装盒中handleOutsideClick
?
尝试使用ref作为字符串是React较旧API的传统方式。
并且他们不建议使用:
如果您以前使用过React,那么您可能会熟悉一个较旧的API,其中ref属性是一个字符串,例如“ textInput”,并且可以通过this.refs.textInput访问DOM节点。我们不建议这样做,因为字符串引用存在一些问题,被认为是旧问题,并且很可能在将来的发行版中删除。
注意:如果您当前正在使用this.refs.textInput访问引用,则建议您使用回调模式或createRef API。
使用React.createRef()
代替,
您可以使用current
ref变量的属性访问它,如下所示:
class Test extends React.Component {
constructor() {
super(props);
this.selectorRef = React.createRef(null);
}
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
handleClickOutside = event => {
console.log(this.selectorRef.current);
}
handleClickInside = () => {
alert("Clicked inside")
}
render = () => {
return (
<ThemeProvider theme={theme}>
<Container disabled={disabled}>
<SelectorDiv
onClick={this.handleClickInside}
ref={selectorRef}
>
<h1>This is the content to click</h1>
</SelectorDiv>
</Container>
</ThemeProvider>
);
};
}
export default Test;
在功能组件中,您可以使用React钩子 useRef()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句