Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onLayout not being called

Tags:

react-native

This is an extract of my code:

render() {
    console.log("first log");
    return (
        <View onLayout={e => console.log("second log")}>
...

The console displays "first log" but not the second one. The view seems to render correctly. I tried with other views but the result is the same. I'm using react-native 0.48.4.

like image 304
AdrienM Avatar asked Sep 24 '17 10:09

AdrienM


1 Answers

I solved this by changing initial height bigger than 0, then onLayout function successfully fired when ChildView's layout has been changed.

  constructor(props) {
    super(props);
    this.state = {
      title: '',
      height: 0 // changed to 1
    };
  }
  onLayout = (event) => {
    console.log('on layout:')
    const {
      x,
      y,
      width,
      height
    } = event.nativeEvent.layout;
    console.log(x, y, width, height);
  }
  render() {
    return (
      <View style={[styles.container, {height: this.state.height}]}>
        <View onLayout={this.onLayout}>
          <ChildView/>
        </View>
      </View>
    )
  }

Due to this Breaking Change: Android: Only call onLayout when layout has actually changed https://github.com/facebook/react-native/wiki/Breaking-Changes#android-only-call-onlayout-when-layout-has-actually-changed-15429e---astreet

like image 72
Jiana Avatar answered Oct 19 '22 17:10

Jiana