Hai . Z
Hai . Z

Reputation: 121

How to call the method by this(React Native)?

renderTopicList(){
    // console.log(this.props);
    //console.log(this.state.dataSource);
    return (
        <ListView
        style={Style.listView}
        ref="listview"
        pageSize={15}
        dataSource={this.state.dataSource}
        renderFooter={this.renderFooter}
        renderRow={this.renderTopicListCell}
       // onEndReached={this.onEndReached}
        automaticallyAdjustContentInsets={false}
        showsVerticalScrollIndicator={false} 
        />
    );
}

renderTopicListCell(data){
    return (
        <TopicListCell
            onSelect = { () => this.selectTopic(data) }
            data={data} />
    );
}
selectTopic(data){

    this.props.navigator.push({
        title: '详细' + (data.replies_count ? '(' + data.replies_count.toString() + '条回复)' : ''),
        component: TopicView,
        passProps: {
            data: data
        }
    });
}

call onSelect in cell : <TouchableHighlight onPress={this.props.onSelect}/>

when I hit the cell,it gives me the following error: _this3.selectTopic is not a function.(In '_this3.selectTopic(data)','_this3.selectTopic' is undefined)

Upvotes: 1

Views: 251

Answers (1)

Bilal Budhani
Bilal Budhani

Reputation: 487

You can solve this issue by two ways.

1) In your component constructor, You can bind the function you want to pass around. For e.g:

constructor() {
  super();

  // Binding the function 
  this.selectTopic.bind(this);
}

then, You can use pass it around with data

renderTopicListCell(data){
    return (
        <TopicListCell
            onSelect={this.selectTopic(data)}
            data={data} />
    );
}

2) You can bind the function when you're passing it.

<TopicListCell onSelect={this.selectTopic.bind(this, data)} data={data} />

I prefer former approach, that way I've all the bind calls at one place and I've to bind it once.

Upvotes: 1

Related Questions