我试图捕获我的 SearchBar 组件之外的所有点击事件,这样我就可以告诉下拉菜单在点击它时关闭。我在网上查找了如何执行此操作的示例,我需要在 javascript 中使用全局变量“文档”。但是,似乎 native react 不支持这一点。有谁知道使用“文档”变量或 React Native 等价物的解决方法?
class Products extends Component {
constructor(props) {
super(props);
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
setWrapperRef(node) {
this.wrapperRef = node;
}
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
alert('You clicked outside of me!');
}
}
componentWillMount() {
this.props.dispatch(getProductList());
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
render() {
const {isLoading, products} = this.props.products;
if (isLoading) {
return <Loader isVisible={true}/>;
}
return (
<View ref={this.setWrapperRef} style={styles.wrapper}>
<Header/>
<View style={styles.bodyWrapper}>
<ScrollView style={styles.scrollView}>
<ProductsContainer data={{productsList: { results: products }}}/>
</ScrollView>
<SearchBar style={styles.searchBar}/>
</View>
<Footer/>
</View>
);
}
}
function mapStateToProps(state) {
const {products} = state;
return {
products
};
}
export default connect(mapStateToProps)(Products);
最佳答案
您不能使用 document
,它是 window
上的一个对象。上面的答案是不正确的,没有考虑到这个平台是 React Native(答案已经被删除)。
要处理点击事件,您需要将所有内容包装在 TouchableWithoutFeedback
中。
<TouchableWithoutFeedback
onPress={this.hideSearchBar}
/>
我会向 TouchableWithoutFeedback
添加一个 zIndex
样式,并在 styles.scrollView
中添加一个。确保 styles.scrollView
中的 zIndex 大于您添加到 TouchableWithoutFeedback 的 zIndex。
关于javascript - 如何在 React Native 中使用变量 'document'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899237/