React Native中点击卡片组件如何获取点击的图片?
解决点击卡片获取对应图片的问题
你遇到的核心问题是没有在点击事件中传递图片相关的参数,而且对React Native本地资源的加载形式有点误解,我来一步步帮你解决:
问题分析
你当前的onPress只是绑定了viewProduct的this指向,但没有传递任何和图片相关的数据,所以函数里的item是undefined;另外,用require()加载的本地图片,它的source返回的是一个资源ID(数字类型),而不是带uri属性的对象——只有网络图片的source才是{ uri: '图片链接' }的形式。
解决方案分两种情况:
情况1:单个固定卡片(像你现在的代码)
直接在onPress里把图片的require结果作为参数传递给viewProduct:
修改你的TouchableOpacity部分:
<TouchableOpacity onPress={() => this.viewProduct(require('../../assets/images/products/product_1.jpg'))} > {/* 你的Card内容保持不变 */} </TouchableOpacity>
然后更新viewProduct函数:
viewProduct = (imageSource) => { console.log('选中的图片资源:', imageSource); // 如果需要在其他地方使用这个图片,直接把imageSource传给Image的source属性即可 }
情况2:循环渲染多个卡片(更常见的场景)
如果是从数组里遍历生成多个产品卡片,先把产品数据统一管理,遍历的时候传递对应的产品对象:
- 先在组件的state里定义产品数组:
constructor(props) { super(props); this.state = { products: [ { id: 1, image: require('../../assets/images/products/product_1.jpg'), price: '₹3500', off: '50% off' }, { id: 2, image: require('../../assets/images/products/product_2.jpg'), price: '₹2200', off: '40% off' } // 更多产品... ] }; }
- 遍历渲染卡片:
{this.state.products.map(product => ( <TouchableOpacity key={product.id} onPress={() => this.viewProduct(product)} > <Card> <CardItem cardBody> <Image source={product.image} style={{ height: 200, width: null, flex: 1 }} /> </CardItem> <CardItem> <Left> <Button transparent> <Text>{product.price}</Text> </Button> </Left> <Right> <Button transparent> <Text style={styles.offText}>{product.off}</Text> </Button> </Right> </CardItem> </Card> </TouchableOpacity> ))}
- 对应的
viewProduct函数:
viewProduct = (product) => { console.log('选中的产品图片:', product.image); // 如果是网络图片,product.image会是{ uri: 'https://xxx.com/img.jpg' },这时可以取product.image.uri }
额外提醒
- 不要用
bind的方式传参(比如this.viewProduct.bind(this, product)),虽然也能工作,但每次渲染都会创建新的函数,可能影响性能,用箭头函数包裹的方式更推荐。 - 本地资源的
require路径不能是动态字符串(比如require(../../assets/${product.imgPath})),必须是静态的,所以提前把所有require结果存在数组里是正确的做法。
内容的提问来源于stack exchange,提问作者Musthafa
相关产品推荐
相关产品推荐

