简体   繁体   中英

How to map object into buttons in React Native?

I am trying to map out an array of objects into buttons on React Native, much like a calculator but I am having trouble doing so. Not sure if I am doing this right as it is breaking my app. I want the layout to be like this image here enter image description here

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 },
];

return (
 <View style={styles.container}>
  <View style={styles.CardPad}>
  {Cards.map((btn) =>
  
    <TouchableOpacity>
      {btn}
    </TouchableOpacity>
  
  )}
  </View>
  <Text>Open up App.js to start working on your app!</Text>
  <StatusBar style="auto" />
</View>
);
}

I'm sure the mapping feature on JS is meant to map out all the buttons to be laid out across a grid. I've done the styling for it but not sure if I should include it here or whether it is making a difference to the function itself. Or am I doing this entirely wrong?

Thanks

Decided to have some fun and show you how I would go about doing this. Here is a url to a codeSandbox: https://codesandbox.io/s/react-native-mapping-object-vh9p5g?file=/src/App.js:143-946

I would make a component to be mapped into. I took the liberty and added some functionality to the TouchableOpacity to help show you how it works in the example. But the basic idea is to do this in the mapping function:

  <View style={styles.cards}>
    {cards.map((i) =>(
        <Card item={i} selectCard={() => setCurrnet(i)} />
      )
    )}
  </View>

You would then map the selectCard into the onPress in the Touchable Opacity in the button:

export const Card = ({ item, selectCard }) => {
  return (
    <TouchableOpacity onPress={selectCard}>
      <View >
        <Text>Card : {item.card}</Text>
        <Text>Count : {item.count}</Text>
      </View>
    </TouchableOpacity>
  );
};

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