Search code examples
androidreact-nativereact-native-listview

How to call renderRow in ListView?


I'm using ListView in react-native. And I want to update ListView by function, so I used this.setState like this.

<Button onPress={()=>this.setState({word:this.state.word})}>Btn</Button>

And after press button, render() method works, but renderRow method not works. So ListView doesn't work. How can I solve it?

Here is my ListView

<ListView
    datasource={this.state.dataSource}
    renderRow={this._renderRow.bind(this)}/>

and my _renderRow

_renderRow(param){
    return(
        <View>{param.word.includes(this.state.word)&&<Text>{param.word}</Text>}</View>
    );
}

I want to update listview when I press Button, and shows up list that param.word includes this.state.word


Solution

  • renderRow is triggered when the DataSource for the ListView is updated. So it seems that your button should update this.state.dataSource rather than this.state.word.

    From: https://facebook.github.io/react-native/docs/listview.html

    In your constructor, you should initialise the DataSource:

    constructor() {
      var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.state = {
        dataSource: ds.cloneWithRows(['row 1', 'row 2']),
      };
    }
    

    Then, you can register the DataSource with the ListView:

    render() {
      return (
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData}</Text>}
        />
      );
    }
    

    When your data changes, you can update the DataSource:

    onDataChanged(newData) {
      var ds = this.state.dataSource.cloneWithRows(newData);
      this.setState({dataSource: ds});
    }
    

    This will trigger your renderRow function.