简体   繁体   English

如何在 React 中将整数值从父道具传递给子道具

[英]How to pass integer value from parent prop to child prop in React

Basically I am working on a dice game where I have a class for Number of sides and another class for Number of dices.基本上我正在开发一个骰子游戏,我有一个关于边数的类和另一个关于骰子数的类。 I want to get values from both classes and pass them to a child class where I will multiply both together to get maxScore .我想从两个类中获取值并将它们传递给一个子类,在那里我将两者相乘以获得maxScore All classes are in same file所有类都在同一个文件中

However, I get NaN as a result.但是,结果我得到了NaN I feel like I am not passing values correctly.我觉得我没有正确传递值。 All classes are in same file.所有类都在同一个文件中。 I am new to React so any help would be appreciated.我是 React 的新手,所以任何帮助将不胜感激。

In both cases you are missing out one of the props values.在这两种情况下,您都错过了props值之一。 So the component tries to multiply undefined with a number and that's why you are getting NaN .因此该组件尝试将undefined与一个数字相乘,这就是您得到NaN的原因。

Think about the following:考虑以下问题:

 console.log(6 * undefined); console.log(undefined * 2);

As a solution you need to provide both values for <Child> component.作为解决方案,您需要为<Child>组件提供两个值。 Try the following:请尝试以下操作:

<Child noOfSides={this.state.mystate} noOfDice={1} />

{/* or */}

<Child noOfDice={this.state.mystate} noOfSides={1}/> 

I hope this explains!我希望这能解释!

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

相关问题 将支持从孩子传给父母React - Pass prop from child to parent React 如何在Vuejs中将父母的道具传给孩子 - How to pass a prop from parent to child in Vuejs 如何将子道具传递给父母? - How to pass child prop to parent? 使用 React Hooks,当我将 prop 从父组件传递给子组件时,子组件中的 prop 未定义 - Using React Hooks, when I pass down a prop from parent to a child component, the prop in the child component is undefined 如何将 React 道具从父母传递给孩子,再传递给另一个孩子? - How do I pass a React prop from Parent to Child, to another Child? 如何在父项更改时将道具传递给反应组件但不更新子项中的该道具? - How do I pass a prop to a react component yet not update that prop in the child when parent changes? 在 REACT.js 中,如何将状态从子组件传递到父组件作为道具 - In REACT.js how can I pass a state from child component up to Parent component as a prop 我如何将来自父母的道具作为上下文传递给它的孩子? - How do i pass a prop from a parent as context to its child? React Native:如何将参数从子组件道具传递给父组件 - React Native: How to pass params to parent component from child component prop Vue - 如何将父引用作为道具传递给孩子? - Vue - How to pass parent ref to child as a prop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM