简体   繁体   English

如何在 React 中为 2 个相同的子组件分配不同的值

[英]How to assign different values to 2 of the same child components in React

For example例如

I have a parent component named.我有一个名为的父组件。 This component contains 2 of the same components called.该组件包含 2 个相同的组件称为。 it looks like this so far到目前为止看起来像这样

<Overview>
  |<Stats>
  |<Stats>

The Stats component contains html that looks like this. Stats 组件包含如下所示的 html。

Pic of Stats Component统计组件的图片

Now the first time I insert <Stats> I want to assign values different from when I insert the second component.现在我第一次插入<Stats>我想分配与插入第二个组件时不同的值。 So in the screenshot there are numbers under each section.因此,在屏幕截图中,每个部分下都有数字。 That is going to be the default numbers every time you insert the <Stats> component.每次插入<Stats>组件时,这将是默认数字。 How can I assign different numbers to every time I insert a <Stats> Component.每次插入<Stats>组件时,如何分配不同的数字。 I don't want the same numbers.我不想要相同的数字。

What I thought about doing was creating States in overview, for example Submitted, Redeemed...etc.我想做的是在概览中创建状态,例如已提交、已赎回……等。 Then in the component retrieve those states but assign itself new values.然后在组件中检索这些状态,但为自己分配新值。 I have read setState needs to be used but for the life of me I cant figure it out.我已阅读 setState 需要使用,但对于我的生活,我无法弄清楚。

Any Help would be greatly appreciated.任何帮助将不胜感激。

You can pass the numbers as props.您可以将数字作为道具传递。 Just give it a name, assign to that name in your opening JSX tag, and then reference it as this.props.yourPropName in the class.只需给它一个名称,在您的开始 JSX 标记中指定该名称,然后在 class 中将其作为 this.props.yourPropName 引用。 (If you are using classes) or props.yourPropName if the component is made with a function) (如果您使用的是类)或 props.yourPropName 如果组件是用函数制作的)

function Stats(props){
//your code
}

<Stats yourPropOne=5 yourPropTwo=3/>

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

相关问题 如何从 React 中的子组件获取值 - How to get values from child components in React React Native:如何从多个相同的子组件设置不同的状态值 - React Native: how to set different state values from multiple identical child components 如何在同一子组件中处理React Native animation.timing - How to deal with React Native animated.timing in same child components 如何在反应中将状态变量值传递给非子组件 - How to pass state variable values to non child components in react 如何模拟在具有不同返回值的不同组件中调用的相同 function - How to mock the same function called in different components with different returned values 最初在``中分配子存储时,如何从子组件访问`react-redux`存储 <Provider> `?&gt; - How can I access `react-redux` store from child components when I initially assign it in `<Provider>`?> React Router:如何有条件地渲染具有相同路由的不同组件 - React Router: How to render different components with the same route conditionally React 如何在同一个父组件上显示多个不同来源的组件 - React how to display multiple components of different origin on the same parent component 如何与 React 中的子组件通信? - How to communicate with child components in React? 根据状态在React中渲染不同的子组件 - Render different child components in React based on state
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM