简体   繁体   中英

How to use state in React Native custom component?

I am trying to create a counter app where certain cards either +1 or -1. As each number on the keypad is clicked the counter increments +1 or -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.

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

What you actually expect is currentCount -> instead of useState={currentCount} you have to write currentCount={currentCount} ; the first currentCount refers to the property which your CardCount-Component expects as a prop. The second currentCount refers to your state-variable in the parent-component.

This will always display a 0 though, the default value.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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