Wilson
Wilson

Reputation: 5

React Native (View) onLayout does not execute functions

I've been trying to get some values from the onLayout prop in a View component.

This is the View that gets returned in the render function:

<View onLayout={this.onLayout}>
    <Text>Hello</Text>
</View>

Then this is the onLayout function that is in the same class

onLayout = () => {
  console.log("hello")
}

The console log is never done. But if I call console.log("hello") from within the onLayout prop it does show in the console.

<View onLayout={console.log("Hello")}>
    <Text>Hello</Text>
</View>

This has had me mindblown for the past 4 hours. I've tried everything I could find here on stackoverflow and GitHub.

Am I just doing something very wrong?

Upvotes: 0

Views: 6453

Answers (1)

yogeshwar nair
yogeshwar nair

Reputation: 813

onLayout(event) {
    const {x, y, height, width} = event.nativeEvent.layout;
    const newHeight = this.state.view2LayoutProps.height + 1;
    const newLayout = {
        height: newHeight ,
        width: width,
        left: x,
        top: y,
      };

    this.setState({ view2LayoutProps: newLayout });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.View1}>
          <Text>{this.state.view2LayoutProps.height}</Text>
        </View>
        <View onLayout={(event) => this.onLayout(event)} 
              style={[styles.View2, this.state.view2LayoutProps]} />
        <View style={styles.View3} />
      </View>
    );
  }

}

Upvotes: 3

Related Questions