问题
I'm trying to implement the loader animation in my react native app but it does't trigger the loader when the button is clicked, although the animating already change to true
.
Check out my code below.
componentWillMount(){
this.hideLoader();
}
showLoader = () => { this.setState({ showLoader:true }); };
hideLoader = () => { this.setState({ showLoader:false }); };
doSignup = () => {
this.showLoader();
}
render() {
console.log(this.state.showLoader);
return (
<View>
<TouchableOpacity style={{ marginTop: 25 }} onPress={this.doSignup}>
<View style={[ styles.button, { backgroundColor: '#5a0060' } ]}>
<Text style={{ fontSize: 20, color: Colors.white }}>Sign Up Now</Text>
</View>
</TouchableOpacity>
<View style={{ position: 'absolute', top: 0, bottom: 0, right: 0, left: 0 }}>
<ActivityIndicator animating={this.state.showLoader} size="small" color="#00ff00" />
</View>
</View>
);
}
When the screen is loaded, I set the loader animation as false
. When the button is clicked only set to true
which should be able to animate the loader but it doesn't appear.
回答1:
I tried to simplify your code to its logical skeleton. I hope this will work and you can start adding styling and etc.
export default class LoginButton extends Component {
state = {
isLoading: false
};
showLoader = () => {
this.setState({ isLoading: true });
};
render() {
return (
<View>
<TouchableOpacity onPress={this.showLoader}>
<Text>Sign Up Now</Text>
</TouchableOpacity>
<ActivityIndicator animating={this.state.isLoading} />
</View>
);
}
}
回答2:
Issue is with the position of ActivityIndicator.
Try removing styling of the Container View, loader will be visible.
<View>
<ActivityIndicator animating={this.state.showLoader} size="small"
color="#00ff00" />
</View>
回答3:
I've made some corrections to your existing code.
I'm mentioning some key changes here:
- View structure
Position in activity indicator view
constructor(props) { super(props); this.doSignup = this.doSignup.bind(this); this.state = { showLoader:false } } showLoader = () => { this.setState({ showLoader:true }); }; hideLoader = () => { this.setState({ showLoader:false }); }; doSignup(){ this.showLoader(); } render() { return ( <View style={{flex:1}}> <TouchableOpacity style={{ marginTop: 25 }} onPress={this.doSignup}> <View style={[ styles.button, { backgroundColor: '#5a0060' } ]}> <Text style={{ fontSize: 20, color: "white" }}>Sign Up Now</Text> </View> </TouchableOpacity> <View style={{ position: 'absolute', top:"50%",right: 0, left: 0 }}> <ActivityIndicator animating={this.state.showLoader} size="large" color="red" /> </View> </View> ); }
来源:https://stackoverflow.com/questions/51763303/show-loader-when-button-is-clicked-in-react-native