3

I'm very new in React Native so forgive my lack of knowledge.

I would like to call a function inside a child but triggered by a parent's event (onScroll here).

return (
    <View
        ref={ref => { this.split = ref; }}
        "onParentScroll"={() => {
        this.split.measureInWindow((x, y, height, width) => {
            console.log('X : ' + x)
            console.log('Y : ' + y)
    })}}>
        {childrenWithProps}
    </View>
)

By the way I can't set an onScroll direcly on the parent scrollView. My goal is having several of this component in a same scrollView.

  • My goal is to get the position of my children at all time so if there is an easier way doing it let me know ;) – Antoine Laget Jul 23 '18 at 09:36
  • I've seen this issue before but my problem here is that i can't send my onScroll to my child and i don't see what to do with that – Antoine Laget Jul 23 '18 at 09:44
  • Can you explain more why you want to do this? Or why chasing the Childs props is not enough? – Colin Jul 23 '18 at 09:53
  • I need to measure my child position each time my scroll view is moving in order to trigger another child event. But i'll have several of these child in a same scrollView so I need they to be independent. – Antoine Laget Jul 23 '18 at 09:57
  • Maybe this question: https://stackoverflow.com/questions/37949981/call-child-method-from-parent – Colin Jul 23 '18 at 10:11
  • I'll try another way, i need to measure the position of several component every time the user scroll (it is always my custom component). – Antoine Laget Jul 23 '18 at 10:58

2 Answers2

1

You can pass a reference to the parent as a prop to the child like so:

<ChildComponent parent={this} />

and from the child, you update the parent's state, passing the a reference to the child itself like so:

this.props.parent.setState({ child1: this });

and finally, in the parent, you handle the updated information according to your needs, like so:

this.state.child1.callAnyMethod();
Eddie Teixeira
  • 332
  • 2
  • 13
0

The easiest way to do so is to send a boolean state as a prop and switch it onScroll.

  <ScrollView
     onMomentumScrollBegin={() => { this.setState({ scroll : !this.state.scroll });}}
 onMomentumScrollEnd={() => { this.setState({ scroll : !this.state.scroll });}}>
        <Trigger trig={ this.state.scroll }><Text>oui</Text></Trigger>
</ScrollView>