简体   繁体   English

如何总结两个 React 道具?

[英]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我想要做的是总结两个包含应用程序从数据库中获取的值的 React props

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在此链接中是完整代码: https : //www.paste.org/111710

Isn't this just <td>{props.player.OBP + props.player.SLG}</td> ?这不就是<td>{props.player.OBP + props.player.SLG}</td>吗? Or if they're not numbers, <td>{parseInt(props.player.OBP) + parseInt(props.player.SLG)}</td> .或者如果它们不是数字, <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 .我建议您使用诸如learnxinyminutesMozilla 的优秀 JS入门之类的东西来复习您的 JS。

I'm not sure exactly what your setup is, but if GPBBAtting is your component, you can do:我不确定您的设置究竟是什么,但如果 GPBBAtting 是您的组件,您可以执行以下操作:

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.你可以用几种方法来做,但我认为这种方法是最简洁的,因为你将求和逻辑排除在返回之外,并且如果你想对其他东西求和,该函数是可重用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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