简体   繁体   中英

Pass Result of Function (Return) as a Prop in ReactJS

In my application, I am attempting to pass the result of number() as a parameter inside a Link. However, it seems like it is attempting to literally pass in the whole function (the raw text of the function), rather than the result (which is really stupid, and doesn't make any sense). What am I missing? Is there a better way to do what I am aiming for? Thanks!

CODE

function number() {
    return 0;
}

<Link to={{pathname: '/path', state: {number: number}}}>Go</Link>

If you want to pass the value of the function you have to do the following:

<Link to={{pathname: '/path', state: {number: number()}}}>Go</Link>

Edit :

I was able to do it like I said before. But in the target component of the Link, the state is inside the props.location . For example, if Link sends to the following Path component, you need to define the props argument in the component and access props.location.state.number like this:

const Path = (props) => (
  <div>
    {props.location.state.number}
  </div>
)

You can view an example working in this link: https://codesandbox.io/s/a-simple-react-router-v4tutorial-9s3f6?fontsize=14&hidenavigation=1&theme=dark

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