首页 > 解决方案 > React Native - 如何设置导入的 js 文件中包含的变量的状态

问题描述

我创建了一个 Loader.js 以在模态中显示 ActivityIndi​​cator。我在所有页面中都包含 Loader.js,并在页面处理/呈现时显示它。

加载器.js

const Loader = props => {
  const {
    loading,
    ...attributes
  } = props;

  return (
    <Modal
      transparent={true}
      animationType={'slide'}
      visible={ loading }
                   onRequestClose={() => { this.setState({loading: false})}}>
      <View style={styles.modalBackground}>
        <View style={styles.activityIndicatorWrapper}>
          <ActivityIndicator
            animating={loading} />
        </View>
      </View>
    </Modal>
  )
}

export default Loader;

在我包含 Loader.js 的屏幕中,我定义了加载状态变量并显示加载器我这样做 this.setState({loading: true});

在渲染屏幕时,我添加了:

      <Loader
          loading={this.state.loading} /> 

但有时加载程序会挂起。我想在模态(Loader.js)中添加一个关闭按钮,为用户提供一种取消加载器的方法。但我无法在 Loader.js 中将加载状态设置为 false。我收到错误:_this.setState 不是函数。

请任何人都可以建议我如何实现关闭装载机?我不想修改包含 Loader.js 的屏幕,因为这需要更改多个屏幕。

任何帮助深表感谢。谢谢你。

标签: react-nativethissetstate

解决方案


我也在使用相同的方法。这是我的 Loader.js :

import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Modal,
    ActivityIndicator
} from 'react-native';

class Loader extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: this.props.isLoading
        }
    }

    static getDerivedStateFromProps(nextProps) {
        return {
          isLoading: nextProps.isLoading
        };
    }     

    render() {
        return (
            <Modal
                transparent={true}
                animationType={'none'}
                visible={this.state.isLoading}
                style={{zIndex: 1100}}
                onRequestClose={() => { }}>
                <View style={styles.modalBackground}>
                    <View style={styles.activityIndicatorWrapper}>
                        <ActivityIndicator animating={this.state.loading} />
                    </View>
                </View>
            </Modal>
        )
    }
}

const styles = StyleSheet.create({
    modalBackground: {
        flex: 1,
        alignItems: 'center',
        flexDirection: 'column',
        justifyContent: 'space-around',
        backgroundColor: '#00000040',
        zIndex: 1000
    },
    activityIndicatorWrapper: {
        backgroundColor: '#FFFFFF',
        height: 100,
        width: 100,
        borderRadius: 10,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-around'
    }
});

export default Loader

并使用如下:

<Loader isLoading={this.state.isLoading} />

isLoading当您在主组件中设置 false时,它​​会自动关闭。


推荐阅读