React-Native : measure a View

后端 未结 3 1152
醉酒成梦
醉酒成梦 2020-12-31 05:05

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

相关标签:
3条回答
  • 2020-12-31 05:25

    To measure view size, no need to use ref at all. You can get it from nativeEvent passed by onLayout.

    measureView(event: Object) {
       console.log(`*** event: ${JSON.stringify(event.nativeEvent)}`);
       // you'll get something like this here:
       // {"target":1105,"layout":{"y":0,"width":256,"x":32,"height":54.5}}
    }
    
    render() {
        return (
            <View onLayout={(event) => {this.measureView(event)}} />
        );
    }
    
    0 讨论(0)
  • 2020-12-31 05:26

    You want to measure the progress bar onLayout.

    var Time = React.createClass({
      getInitialState: function() {
        return({ progressMaxSize: 0 }); 
      },
      measureProgressBar: function() {
        this.progressBar.measure(this.setWidthProgressMaxSize);
      },
      setWidthProgressMaxSize: function(ox, oy, width, height, px, py) {
        this.setState({ progressMaxSize: width });
      },
      render: function() {
        return(
          <View style={listViewStyle.time} ref={(c) => { this.progressBar = c; } onLayout={this.measureProgressBar}>
            <View style={listViewStyle.progressBar} >
              <View style={[listViewStyle.progressMax, { width: this.state.progressMaxSize }]}/>
            </View>
          </View>
        );
      }
    });
    
    0 讨论(0)
  • 2020-12-31 05:38

    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

    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 })
      );
    }
    
    0 讨论(0)
提交回复
热议问题