简体   繁体   English

如何在 React Native 自定义组件中使用状态?

[英]How to use state in React Native custom component?

I am trying to create a counter app where certain cards either +1 or -1.我正在尝试创建一个计数器应用程序,其中某些卡是 +1 或 -1。 As each number on the keypad is clicked the counter increments +1 or -1.当点击键盘上的每个数字时,计数器会增加 +1 或 -1。 So far I've created a custom component and trying to use state in order to到目前为止,我已经创建了一个自定义组件并尝试使用状态来

export default function App() {

  const cards = [
    { card: "A", count: -1 },
    { card: "K", count: -1 },
    { card: "Q", count: -1 },
    { card: "J", count: -1 },
    { card: 10, count: -1 },
    { card: 9, count: 0 },
    { card: 8, count: 0 },
    { card: 7, count: 0 },
    { card: 6, count: 1 },
    { card: 5, count: 1 },
    { card: 4, count: 1 },
    { card: 3, count: 1 },
    { card: 2, count: 1 },
  ];


  const [currentCount, setCount] = useState(0); //Count <<

  return (
    <View style={styles.app}>
      <CardCount useState={currentCount}/> // Custom component <<
      <View style={styles.cards}>
      {cards.map((index) =>(<Card item={index}/>))}
      </View>
    </View>
  );
}

The custom component 

export const CardCount = ({currentCount}) => {
  return (
    <Text>{currentCount}</Text>
  )
}

I am not seeing any results for this?我没有看到任何结果? Unless I am using the state wrong除非我使用错误的状态

Thanks a lot非常感谢

your custom component should be like this to show received props您的自定义组件应该是这样来显示收到的道具

export const CardCount = ({useState}) => {
  return (
    <Text>{useState}</Text>
  )
}
<CardCount useState={currentCount}/>

This line of code says that your CardCount Component-Props consist of an object with a useState property.这行代码表明您的 CardCount Component-Props 包含一个具有 useState 属性的对象。

export const CardCount = ({currentCount}) => {

What you actually expect is currentCount -> instead of useState={currentCount} you have to write currentCount={currentCount} ;您实际期望的是 currentCount -> 而不是 useState={currentCount} 您必须编写 currentCount={currentCount} ; the first currentCount refers to the property which your CardCount-Component expects as a prop.第一个 currentCount 是指您的 CardCount-Component 期望作为道具的属性。 The second currentCount refers to your state-variable in the parent-component.第二个 currentCount 指的是父组件中的状态变量。

This will always display a 0 though, the default value.不过,这将始终显示 0,即默认值。

To be able to modify the count value, you could wrap your setCount function in a callback , add this function to your Card as a prop and then create an onClick-event on the card which calls the props-callback with some value.为了能够修改计数值,您可以将 setCount 函数包装在一个回调中,将此函数作为道具添加到您的卡片中,然后在卡片上创建一个 onClick 事件,该事件会使用一些值调用道具回调。

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

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