react-native 圆形‘正在加载’提示符号 ActivityIndicator

dialog
小例子,显示和隐藏圆形进度条,涉及到的属性:
animating: 默认为显示 true
color:默认有颜色
size:默认为 small ,可选 large ,android设备上可直接填数字
hidesWhenStopped:当animating和hidesWhenStopped都为fales时,显示进度条静止的状态。

代码
export default class App extends Component{

  constructor(props){
      super(props);
      this.state ={
        isShow:true
      }
  }

  onPressTop(){
      this.setState({
          isShow:true
      })
  }
    onPressBoot(){
        this.setState({
            isShow:false
        })
    }
  render() {
    return (
      <View style={styles.container}>
          <ActivityIndicator size={100} animating={this.state.isShow}
          color="#0000ff"></ActivityIndicator>

          <Button title="显示"
                  onPress={this.onPressTop()}
          />

          <Button title="隐藏"
                  onPress={this.onPressBoot()}
          />

      </View>
    );
  }
}

这样写会出现以下问题
死循环
当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生死循环。
当render函数渲染界面时,又重新调用了setState。setState就会重新渲染界面,所以发生错误。
正确方法,bind;

 onPress(state){
        this.setState({
            isShow:state
        })
    }
...
		 <Button title="显示"
                  onPress={this.onPress.bind(this,true)}
          />

          <Button title="隐藏"
                  onPress={this.onPress.bind(this,false)}
          />

bind就是将处理函数和指定的操作绑定在一起。操作触发时函数执行。
也可以直接用箭头函数

		  <Button title="显示"
                  onPress={() => this.setState({
                      isShow:true
                  })}
          />

          <Button title="隐藏"
                  onPress={() => this.setState({
                      isShow:false
                  })}
          />

箭头函数也可以直接完成bind绑定,它会绑定当前scope的this引用。这个只是ES6的写法。

猜你喜欢

转载自blog.csdn.net/weixin_36965072/article/details/84954048
今日推荐