react-native - 获取从子组件传递的道具
问题描述
我有一个反应原生应用程序,我在 App.js 中渲染地图,这是 App.js 的状态:
this.state = {
region: null,
shops: [
{
name: "name",
rating: 0,
coords: {
latitude: 543543,
longitude: 656546
}
}
]
};
这是它的渲染代码:
render() {
const { region, shops } = this.state;
return (
<SafeAreaView style={styles.container}>
<Map region={region} places={shops} />
</SafeAreaView>
);
}
如您所见,我将商店状态传递给地图组件,在地图组件中,我有这个主渲染来渲染 MapView:
render() {
const region = this.props.region;
return (
<MapView
style={styles.container}
region={region}
showsUserLocation
showsMyLocationButton
>
{this.renderMarkers()}
</MapView>
);
您可以看到存在商店标记的 this.renderMarkers() :
renderMarkers() {
return this.props.places.map((marker, i) => (
<Marker key={i} title={marker.name} coordinate={marker.coords} >
<View style={{
flexDirection: 'row', width: 70, height: 60,
backgroundColor: 'none',
}}>
<Svg
width={60} height={50}>
<Image
href={require('icon.png')}
/>
<Rating rating={marker.rating} />
</Svg>
</View>
</Marker>
));
}
每个标记都包含图像和评级组件以及我正在尝试做的事情以将评级传递如下: rating={marker.rating} 到评级组件
现在在评级组件中,我试图获得这样的评级:
render() {
let ratings = this.props.places;
let stars = [];
for (var i = 1; i <= 5; i++) {
if (i > ratings.rating) {
// do something
}
}
return (
<View style={styles.container}>
{ stars }
</View>
);
}
现在您了解我将状态的整个对象从 App 组件传递到 Map 组件然后我只想将评级道具从 Map 组件传递到 Rating 组件怎么做?
解决方案
当您说评级组件时,您是指<Star>
组件吗?我注意到在我认为属于<Star>
组件的最后一段代码中,您尝试不正确地访问它的道具。如果你使用
<Star rating = { marker.rating } />
那么您应该rating
在组件中获得该道具,Star
例如:
const { rating } = this.props;
推荐阅读
- python - 如何根据值对矩阵中的行进行重新排序?
- bash - 已解决:Catalina bash shopt direxpand 丢失
- php - PHP - 遇到格式不正确的数值
- react-native - React Native 中的 Android 动态资产交付
- c++ - 我可以以这种方式为链表实现 push_back 方法吗?
- javascript - 数组分组转换键 start_section 到 end_section
- python - 如何将 pandas 数据框中的数字列与 NaN 结合起来?
- php - Wordpress 过滤自定义帖子类型分类
- android - 我们应该在购买成功后解锁应用内商品(onPurchasesUpdated),还是在确认成功后解锁(onAcknowledgePurchaseResponse)?
- python - 时间模块在 Pycharm 中不起作用(我使用的是 Python 3.8.5、Pycharm 和 Pygame)