react-native - React Native - 如何设置导入的 js 文件中包含的变量的状态
问题描述
我创建了一个 Loader.js 以在模态中显示 ActivityIndicator。我在所有页面中都包含 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 的屏幕,因为这需要更改多个屏幕。
任何帮助深表感谢。谢谢你。
解决方案
我也在使用相同的方法。这是我的 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时,它会自动关闭。
推荐阅读
- flutter - 无法使用颤振创建创建颤振应用
- r - 为什么 R 会引入 NA?没有逗号,只有简单的数字,比如 4438
- postgresql - 有什么办法可以克服 tsvector 和 tsquery 在 postgres 全文搜索中的限制
- robotframework - 在 Robotframework 中未动态设置变量
- javascript - 如何在javascript中计算数组中的每个元素数
- windows - 如何使用 AutoHotkey 激活后台进程?
- python - Python:Django:如何使用 python 脚本运行 django 应用程序
- amazon-web-services - AWS 密钥对替换
- html - 使用 css 更改部分 SVG 颜色
- hash - 我什么时候应该选择 murmur 或 cityhash 而不是 ie。沙256?