如何在本机反应中使用变量“文档”?

Fai*_*een 5 javascript reactjs react-native

我正在尝试捕获 SearchBar 组件之外的所有点击事件,以便我可以在单击时告诉下拉菜单关闭。我在网上查找了如何执行此操作的示例,我需要在 javascript 中使用全局变量“文档”。但是,似乎 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);
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在此处输入图片说明

Dan*_*Dan 4

你不能使用document,它是 上的一个对象window。上面的答案是不正确的,并且没有考虑到这个平台是 React Native(答案已被删除)。

要处理点击事件,您需要将所有内容包装在TouchableWithoutFeedback.

<TouchableWithoutFeedback
  onPress={this.hideSearchBar}
/>
Run Code Online (Sandbox Code Playgroud)

我会zIndexTouchableWithoutFeedback和 中添加一种样式styles.scrollView。确保其中的 zIndexstyles.scrollView大于您添加到 TouchableWithoutFeedback 中的 zIndex。