简体   繁体   中英

How to sum two React props?

What I wanna do is sum two React props that contain values that the App is fetching from a database

Here's the props snippet

const GPBBatting = (props) => (
  <tr>
    <td>{props.player.Player}</td>
    <td>{props.player.G_GS.substring(0, 1)}</td>
    <td>{props.player.AB}</td>
    <td>{props.player.R}</td>
    <td>{props.player.H}</td>
    <td>{props.player.H2}</td>
    <td>{props.player.H3}</td>
    <td>{props.player.HR}</td>
    <td>{props.player.RBI}</td>
    <td>{props.player.SB_ATT}</td>
    <td>{props.player.BB}</td>
    <td>{props.player.SO}</td>
    <td>{props.player.BA}</td>
    <td>{props.player.OBP}</td>
    <td>{props.player.SLG}</td>

    <<<<<<I want the sum of OBP + SLG values here>>>>>

    <td>{props.player.TB}</td>
    <td>{props.player.SH}</td>
    <td>{props.player.SF}</td>
  </tr>
);

And here in this link is the complete code: https://www.paste.org/111710

Isn't this just <td>{props.player.OBP + props.player.SLG}</td> ? Or if they're not numbers, <td>{parseInt(props.player.OBP) + parseInt(props.player.SLG)}</td> .

I'd recommend brushing up on your JS with something like learnxinyminutes or Mozilla's excellent JS primers .

I'm not sure exactly what your setup is, but if GPBBAtting is your component, you can do:

const GPBBatting = (props) => (

const getPlayerSum = (a, b) => {
      const sumValue = a + b;
      return sumValue
}

return(
  <tr>
    <td>{props.player.Player}</td>
    <td>{props.player.G_GS.substring(0, 1)}</td>
    <td>{props.player.AB}</td>
    <td>{props.player.R}</td>
    <td>{props.player.H}</td>
    <td>{props.player.H2}</td>
    <td>{props.player.H3}</td>
    <td>{props.player.HR}</td>
    <td>{props.player.RBI}</td>
    <td>{props.player.SB_ATT}</td>
    <td>{props.player.BB}</td>
    <td>{props.player.SO}</td>
    <td>{props.player.BA}</td>
    <td>{props.player.OBP}</td>
    <td>{props.player.SLG}</td>

    {getPlayerSum(props.player.SLG, props.player.OBP)} // call a sum function here and pass the values you want to sum

    <td>{props.player.TB}</td>
    <td>{props.player.SH}</td>
    <td>{props.player.SF}</td>
  </tr>
)
);

You could do it a few ways, but I think this way is neatest because you keep the sum logic out of the return and the function is reusable if you want to sum other things.

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