Pooya Behravesh
Pooya Behravesh

Reputation: 194

calling prop from child component in a function dosen't work

I want to pass a prop from child to parent component(exactly, call a function in parent when some work done in child). but it dosen't work such that i want!

this is some codes of child compomnent:

  handle = () =>
    {
      return this.props.DoLoggin;
    }
  render(){
    return(
    <Button  onPress={this.handle}><Text>Click</Text></Button>
    );
  }

and parent :

handler = ()=> {
console.log('Logged In :)');
}
render(){
return (
<Login DoLoggin={this.handler}/>
);
}

Note : when i use the call prop in a method like onPress in Child component , it works! :

render(){
return(
<Button onPress={this.props.DoLoggin}><Text>Click</Text></Button>
);
}

But that is not what i want! i want call prop, in a function to do some work automatically!

Upvotes: 0

Views: 103

Answers (2)

Ian Vasco
Ian Vasco

Reputation: 1340

The reason it worked directly is because you were not calling the function itself. It is just a reference to the function that will be called when user presses the Button. Since you are using your custom handler, you have to call the function in the return statement

You have to call the prop function inside your handle function.

  handle = () =>
    {
      return this.props.DoLoggin();
    }

Upvotes: 2

MrAleister
MrAleister

Reputation: 1581

You have to call it:

handle = () =>
{
  return this.props.DoLoggin(); //not this.props.DoLoggin;
}

Upvotes: 1

Related Questions