React-Native:测量视图 [英] React-Native : measure a View
问题描述
我正在尝试使用ref
测量视图,但是尽管我看到屏幕上显示的视图,但返回的width
为0(并且远非等于0).
I'm trying to measure a view using a ref
, but the width
returned is 0 despite the fact that I see the view displayed on the screen (and it's far from being equal to 0).
我尝试遵循以下方法: https://github.com/facebook/react- native/issues/953 ,但它不起作用...我只想获取View的实际宽度.
I tried to follow this : https://github.com/facebook/react-native/issues/953 but it just doesn't work ... I just want to get the actual width of the View.
这是我的代码:
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,
},
推荐答案
一夜之间,一些人谈论了一个(hacky)解决方案,但是它解决了我的问题,在这里找到了它:
During the night some guys talked about a (hacky) solution but it solved my problem, found it here: https://github.com/facebook/react-native/issues/953
基本上,解决方案是使用setTimeout
,一切都可以神奇地工作:
Basically the solution is to use setTimeout
and everything just works magically:
componentDidMount: function() {
setTimeout(this.measureProgressBar);
},
measureProgressBar: function() {
this.refs.progressBar.measure((a, b, width, height, px, py) =>
this.setState({ progressMaxSize: width })
);
}
这篇关于React-Native:测量视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!