首页 > 解决方案 > 获取从子组件传递的道具

问题描述

我有一个反应原生应用程序,我在 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 组件怎么做?

标签: react-nativeexpo

解决方案


当您说评级组件时,您是指<Star>组件吗?我注意到在我认为属于<Star>组件的最后一段代码中,您尝试不正确地访问它的道具。如果你使用

<Star rating = { marker.rating } />

那么您应该rating在组件中获得该道具,Star例如:

const { rating } = this.props;

推荐阅读