【发布时间】:2018-02-14 09:32:23
【问题描述】:
我创建了一个组件调用 Spinner 所以:
//spinner.js
import React, { Component } from 'react';
import {
Image,
StyleSheet,
View,
Text,
KeyboardAvoidingView,
TouchableHighlight,
Modal,
Button,
ActivityIndicator,
} from 'react-native';
export default class Spinner extends Component{
constructor(props){
super(props);
this.state={
visible:this.props.visible
};
this._show=this._show.bind(this);
this._hide=this._hide.bind(this);
}
render(){
return(
<Modal
animationType={'none'}
transparent={true}
visible={this.state.visible}
onRequestClose={this.props.onDismissLoadingCallback}>
<View style={{flex:1}}/>
<View style={{
height:80,
width:80,
alignItems:'center',
justifyContent:'center',
backgroundColor:'#3434347f',
borderRadius:10,alignSelf:'center'}}>
<ActivityIndicator
animating={true}
size={"large"}
color={'white'}
/>
</View>
<View style={{flex:1}}/>
</Modal>
);
}
_show() {
this.setState({visible:true});
}
_hide(){
this.setState({visible:false});
}
}
在此创建方法 _show() 和 _hide()
但是从其他类调用时不起作用,我从类 Login.js 调用
class Login extends Component {
constructor(props) {
super(props)
this.state = { visible: false };
}
_onLoginPress() {
this.Spinner._show()
)
}
_redirect() {
this.Spinner._hide()
}
render() {
return (
<Spinner visible= {this.state.visible}/>
<TouchableHighlight style={styles.button}
onPress={this._onLoginPress}
activeOpacity={1} >
<Text style={styles.textButtonLogin}>Visible</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.button}
onPress={this._redirect}
activeOpacity={1} >
<Text style={styles.textButtonLogin}>Not Visible</Text>
</TouchableHighlight>
)
}
在构造函数中设置为true时显示,但在构造函数中设置为false时不显示,按下按钮_onLoginPress时显示,按下按钮_redirect()时不显示。
【问题讨论】:
-
为什么不直接将“可见”道具传递给 Spinner 组件中的模态,并在登录组件中更新可见状态而不是调用显示和隐藏?通常最好避免使用 refs 并使用 state 和 peops 来代替。
标签: react-native progress-bar components