我试图用ref来测量一个视图,但返回的width是0,尽管我看到屏幕上显示的视图(它远远不等于0).

我试着遵循这个:https://github.com/facebook/react-native/issues/953,但它就是不起作用...我只想得到视图的实际宽度.

这是我的代码:

var Time = React.createClass({
  getInitialState: function() {
    return({ progressMaxSize: 0 }); 
  },
  componentDidMount: function() {
    this.measureProgressBar();
  },
  measureProgressBar: function() {
    this.refs.progressBar.measure(this.setWidthProgressMaxSize);
  },
  setWidthProgressMaxSize: function(ox, oy, width, height, px, py) {
    this.setState({ progressMaxSize: width });
  },
  render: function() {
    return(
      <View style={listViewStyle.time} ref="progressBar">
        <View style={listViewStyle.progressBar} >
          <View style={[listViewStyle.progressMax, { width: this.state.progressMaxSize }]}/>
        </View>
      </View>
    );
  }
}); 

关联的样式:

time: {
    position: 'absolute',
    bottom: 5,
    left: 5,
    right: 5,
    backgroundColor: '#325436',
    flexDirection: 'row',
  },
  progressBar: {
    flex: 1,
    backgroundColor: '#0000AA',
  },
  progressMax: {
    position: 'absolute',
    top: 0,
    left: 0,
    backgroundColor: '#000',
    height: 30, 
  },

推荐答案

晚上,一些人谈论了一个(黑客)解决方案,但它解决了我的问题,在这里找到了:https://github.com/facebook/react-native/issues/953

基本上,解决方案是使用setTimeout,所有东西都能神奇地工作:

componentDidMount: function() {
  setTimeout(this.measureProgressBar);
},

measureProgressBar: function() {
  this.refs.progressBar.measure((a, b, width, height, px, py) =>
    this.setState({ progressMaxSize: width })
  );
}

React-native相关问答推荐

Redux toolkit通过按钮操作进行查询

react 在顶部选项卡导航中传递本机数据

@react-native-community/cli-platform-ios/native_modules' 来自哪里?

什么是 expoClientId?

获取 TypeError:this.InnerNativeModule.configureProps 不是 mac 上 expo 中的函数

从 React 原生 Js 代码调用 Android Native UI 组件方法

react-native: 'adb' 不是内部或外部命令、可运行程序或批处理文件

React Native - ScrollView 中的 ListView 分页?

Undefined 不是判断 this.state.* 的对象

Realm 和 React Native - 实现自动更新的最佳实践?

redux saga 的delay延迟功能不起作用

如何从 React Native 应用程序打开 Google Play store ?

如何在 ubuntu 上安装 facebook watchman?

是否可以将 Image.getSize 与静态图像文件一起使用?

如何将 Crashlytics 与 React Native 应用程序集成

如何将props传递给 React Navigation 导航器中的组件?

React-Native ios App 在没有报告的情况下崩溃

使用 React Native 和 Redux 的动画状态管理

react-native-webview :对于 iOS 文本太小

无法读取未定义的属性 string| React.PropTypes | LayoutPropTypes.js