访问ref react native onpress

时间:2018-07-25 08:07:56

标签: javascript ios react-native

我用来显示视图列表以及标记列表。我想将标记与Animated.scrollview链接,但是使用ref无效(我可能以错误的方式使用ref)

有我的工作

return (
  <View style={styles.container}>
    <MapView
      ref={map => this.map = map}
      initialRegion={this.state.region}
      style={styles.container}
    >
      <UrlTile
        urlTemplate="http://IP:8080/styles/klokantech-basic/{z}/{x}/{y}.png"
        zIndex={-1}
      />
      {this.state.markers.map((marker, index) => {

        return (
          <MapView.Marker key={index} coordinate={marker.coordinates} onPress={() => this.myRef.scrollTo({x: 0, y: 0})
        } >
            <Animated.View style={[styles.markerWrap, opacityStyle]} >
              <Animated.View style={[styles.ring, scaleStyle]} />
              <View style={styles.marker} />
            </Animated.View>
          </MapView.Marker>
        );

      })}
    </MapView>
    <Animated.ScrollView
      horizontal
      ref={c => (this.myRef = c)}
      scrollEventThrottle={1}
      showsHorizontalScrollIndicator={true}
      snapToInterval={CARD_WIDTH}
      onScroll={Animated.event(
        [{
          nativeEvent: {
            contentOffset: {
              x: this.animation,
            },
          },
        },],
        { useNativeDriver: true }
      )}
      style={styles.scrollView}
      contentContainerStyle={styles.endPadding}
    >
      {this.state.markers.map((marker, index) => {
          return (
            <View style={styles.card} key={index}>
              <Image
                source={marker.image}
                style={styles.cardImage}
                resizeMode="cover"
              />
              <View style={styles.textContent}>
                <Text numberOfLines={1} style={styles.cardtitle}>{marker.espace.titre}</Text>
                <Text numberOfLines={1} style={styles.cardDescription}>
                  {marker.description}
                </Text>
              </View>
            </View>)
      })
      }
    </Animated.ScrollView>
  </View>
);

当我尝试调用this.myRef.scrollTo({x:0,y:0}时,我得到_this4.myRef.scrollTo不是函数

1 个答案:

答案 0 :(得分:0)

我认为您需要更换裁判,应该可以正常工作:

// MapView
ref={map => {if (map) this.map=map}}

// Animated.ScrollView
ref={c => {if (c) this.myRef=c}}

更新

// there is typo in your code
// Animated.ScrollView
ref={c => (this.myRef = c)}