Call the parent function from the child component in the React-Native ListView row

I saw several examples of this question, but I could not get them to work, or completely understand how it all fits together. I have a component called ParentListView and the other is ChildCell (a line in the View list). I want onPress from ChildCell call a function in ParentListView .

 class ChildCell extends Component { pressHandler() { this.props.onDonePress; } render() { return ( <TouchableHighlight onPress={() => this.pressHandler()} > <Text>Child Cell Button</Text> </TouchableHighlight> ); } } 

and ParentListView :

 class ParentListView extends Component { //... render() { return ( <ListView dataSource={this.state.dataSource} style={styles.listView} renderRow={this.renderCell} renderSectionHeader={this.renderSectionHeader} /> ); } renderCell() { return ( <ChildCell onDonePress={() => this.onDonePressList()} /> ) } onDonePressList() { console.log('Done pressed in list view') } } 

I think this is all suitable code. I can get the press to register wanting ChildCell , but I can’t get a way to shoot at ParentListView . What am I missing?

Thanks in advance!

UPDATE 1:

in ParentListView if I changed the details that went with this:

 <ChildCell onDonePress={this.onDonePressList.bind(this)} /> 

I get Unhandled JS Exception: null is not an object (evaluating 'this.onDonePressList') at compile time when rendering a cell.

If I put console.log directly as follows:

 <ChildCell onDonePress={() => console.log('Done pressed in list view')} /> 

he writes the message in order.

If I leave it as originally:

 <ChildCell onDonePress={() => this.onDonePressList()} /> 

It is reset to buttonPress using Unhandled JS Exception: null is not an object (evaluating '_this2.onDonePressList')

UPDATE 2:

OK, I tried to bind the method in the constructor like this:

 class ParentListView extends Component { constructor(props) { super(props); this.onDonePressList = this.onDonePressList.bind(this); this.state = {...}; } 

but it gives me this error: null is not an object (evaluating 'this.onDonePressList') and will not work.

UPDATE 3: Here is the link to respond to the home site

+7
function listview react-native components row
source share
1 answer

Try calling onDonePress in pressHandler as follows:

 pressHandler() { this.props.onDonePress() } 

Also, bind this to your renderRow and renderSectionHeader :

 <ListView dataSource={this.state.dataSource} style={styles.listView} renderRow={this.renderCell.bind(this)} renderSectionHeader={this.renderSectionHeader.bind(this)} /> 

I created an example here using the function above.

https://rnplay.org/apps/DcdAuw

+6
source share

All Articles