今天碰到一個很奇葩的問題,後來在stackoverflow上面查,據說是react-native的一個bug。
原帖地址:http://stackoverflow.com/questions/38579665/reactnative-activityindicator-not-showing-when-animating-property-initiate-false
比如如下代碼:
constructor(props) {
super(props);
this.state = {
animating: true,
};
}
test() {
this.setState(animationg: 。this.state.animating);
}
render() {
return(
<View>
<Button onPress = {this.test.bind(this)}>
</Button>
<ActivityIndicator animating = {this.state.animating} />
</View>
);
}
在這種情況下(animating初始值為true),可通過點擊button實現載入框的顯示和隱藏,達到預期效果。
但如果animating的初始值為false,如下所示:
constructor(props) {
super(props);
this.state = {
animating: false,
};
}
test() {
this.setState(animationg: 。this.state.animating);
}
render() {
return(
<View>
<Button onPress = {this.test.bind(this)}>
</Button>
<ActivityIndicator animating = {this.state.animating} />
</View>
);
}
則無論如何點擊button,都無法將載入框顯示出來。
後來在react-native官方github上看到這個問題的一個神奇的解決方案,原帖地址: https://github.com/facebook/react-native/issues/11682
只需將
<ActivityIndicator animating = {this.state.animating} /> 改為 {this.state.animating && <ActivityIndicator animating={this.state.animating} />}
即可正常運行。
完整代碼如下:
constructor(props) {
super(props);
this.state = {
animating: false,
};
}
test() {
this.setState(animationg: 。this.state.animating);
}
render() {
return(
<View>
<Button onPress = {this.test.bind(this)}>
</Button>
{this.state.animating && <ActivityIndicator animating={this.state.animating} />}
</View>
);
}
<Button onPress = {this.test.bind(this)}>
</Button>