react-native-snap-corousel:如何在项目单击时调用函数

时间:2018-06-26 07:04:33

标签: react-native react-native-snap-carousel

我想在单击皮质中的项目时调用一个函数。下面是我的代码。

private async void Form1_Load(object sender, EventArgs e)
{
    //client is a HttpClient
    //byteContent is a ByteArrayContent
    var PostTask = client.PostAsync("theUrl", byteContent);
    PostTask.Wait(); //blocking here

    using (HttpResponseMessage response = PostTask.Result)
    {
        response.EnsureSuccessStatusCode();
       Trace.WriteLine(response.ToString());
    }

}

当我单击该项目时,出现错误,提示 onPress(){ console.log("onPress"); } _renderItem({item, index}) { return ( <TouchableWithoutFeedback onPress={this.onPress.bind(this)}> <View style={styles.slide}> <Image source={{ uri: item.row.image_name }} style={styles.image} /> </View> </TouchableWithoutFeedback> ); }

我可以通过如下所示的点击直接提醒。

_this6.onPress is not a function

如何在Item click上调用方法?

演示代码:https://snack.expo.io/SJtm1vJMX

1 个答案:

答案 0 :(得分:3)

所有功能都必须绑定到this的宽松上下文中。这意味着您也需要做this._renderItem.bind(this)

示例 (为简单起见,删除了一些部分)

export default class ImageCarousel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      slider1ActiveSlide: SLIDER_1_FIRST_ITEM,
    };
    this._renderItem = this._renderItem.bind(this);
    this.onPress = this.onPress.bind(this);
  }
  onPress() {
    Alert.alert('Hi');
  }
  _renderItem({ item, index }) {
    return (
      <TouchableOpacity onPress={this.onPress}>
        <Image style={styles.image} source={{ uri: item.illustration }} />
      </TouchableOpacity>
    );
  }

  mainExample(number, title) {
    const { slider1ActiveSlide } = this.state;
    return (
      <View>
        <Carousel
          ref={c => (this._slider1Ref = c)}
          data={ENTRIES1}
          renderItem={this._renderItem}
          {/* ... */}
        />
        {/* ... */}
      </View>
    );
  }

  render() {
    const example1 = this.mainExample(
      1,
      'Default layout | Loop | Autoplay | Scale | Opacity | Pagination with tappable dots'
    );
    return <ScrollView>{example1}</ScrollView>;
  }
}