繁体   English   中英

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

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

我正在尝试创建一个计数器应用程序,其中某些卡是 +1 或 -1。 当点击键盘上的每个数字时,计数器会增加 +1 或 -1。 到目前为止,我已经创建了一个自定义组件并尝试使用状态来

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>
  )
}

我没有看到任何结果? 除非我使用错误的状态

非常感谢

您的自定义组件应该是这样来显示收到的道具

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

这行代码表明您的 CardCount Component-Props 包含一个具有 useState 属性的对象。

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

您实际期望的是 currentCount -> 而不是 useState={currentCount} 您必须编写 currentCount={currentCount} ; 第一个 currentCount 是指您的 CardCount-Component 期望作为道具的属性。 第二个 currentCount 指的是父组件中的状态变量。

不过,这将始终显示 0,即默认值。

为了能够修改计数值,您可以将 setCount 函数包装在一个回调中,将此函数作为道具添加到您的卡片中,然后在卡片上创建一个 onClick 事件,该事件会使用一些值调用道具回调。

暂无
暂无

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

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