简体   繁体   English

如何将对象映射到 React Native 中的按钮?

[英]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.我正在尝试将一组对象映射到 React Native 上的按钮中,就像计算器一样,但我在这样做时遇到了麻烦。 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.我确信 JS 上的映射功能旨在映射出所有要在网格中布局的按钮。 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这是 codeSandbox 的 url: 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.我冒昧地向 TouchableOpacity 添加了一些功能,以帮助您展示它在示例中的工作原理。 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:然后,您将 selectCard 映射到按钮的 Touchable Opacity 中的 onPress 中:

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

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

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