【问题标题】:get product id set in const use onPress in react native loop获取在 const 中设置的产品 ID 在反应本机循环中使用 onPress
【发布时间】:2021-02-22 11:00:24
【问题描述】:

我想在 pid 使用 onPress 中添加 key={item.id} 值,并且她的数据在 react native 中进入数据库使用循环

const addToWishlist = () => {
     const [pid, setPid] = useState('');
}
return (
  <>
   {ProductData.map((item, index) => {
     return (
       <View key={index} style={styles.prod}>
         <TouchableOpacity onPress={addToWishlist} key={item.id}>
           <Feather name="heart" color={heartColor} style={{fontSize:16}}/>
         </TouchableOpacity>
       </View>
     )
   })}
  </>
)

【问题讨论】:

    标签: react-native onpress


    【解决方案1】:

    你的函数应该接受一个参数id,并且你必须在onPress被触发时发送它。

    onPress={() =&gt; addToWishlist(item.id)}

    const addToWishlist = (id) => {
      console.log(id)
      // const [pid, setPid] = useState('');
      // You should not declare a hook in a function
    }
    
    return (
      <>
       {ProductData.map((item, index) => (
         <View key={index} style={styles.prod}>
           <TouchableOpacity onPress={() => addToWishlist(item.id)} key={item.id}>
             <Feather name="heart" color={heartColor} style={{fontSize:16}}/>
           </TouchableOpacity>
         </View>
       )})
     </>
    )
    

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 2017-11-09
      • 2018-06-22
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多