简体   繁体   中英

How to pass a function as a prop into a route React js?

I have taken a look at many other stack overflow questions that look similar to my question but none of them have been any help.

So here is what I am trying to do.

in App.js: Basically I made a function singedInToggleHandler that I want to use in the linked page.

signedInToggleHandler = () => {
    this.setState( (prev) => {
      return {signedIn: !prev.signedIn};
    });
  };

<Route path = '/Login' component = {LoginScreen} 
                render = { (props) => (<LoginScreen SignedInToggleHandler = {this.signedInToggleHandler}/>)}/>

The last line above is how I am passing in the function.

I access it then in LoginScreen.js

 formType = <SignIn SignedInHandler = {props.SignedInToggleHandler}/>

only to pass it to another component SignIn.js

SignIn.js

function handleSubmit(event){
        console.log("Submitted");
        event.preventDefault();
        console.log(email,password);
        const user = SignIn(email,password);
        console.log(user);
        props.SignedInToggleHandler();
    }

Now this is the last place I access it. Over here I want to use SignedInToggleHandler() that I got from App.js but I receive the error message :

在此处输入图片说明

Thank you so much for your time and help!

Your error is here

<Route path = '/Login' component = {LoginScreen} 
                render = { (props) => (<LoginScreen SignedInToggleHandler = {this.signedInToggleHandler}/>)}/>

You're using component props with render function. But as per doc ,

Warning: <Route component> takes precedence over <Route render> so don't use both in the same <Route> .

To resolve, remove component prop. render prop will do it work.

<Route path = '/Login' 
                    render = { (props) => (<LoginScreen SignedInToggleHandler = {this.signedInToggleHandler}/>)}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM