Working with a ListView in React-Native, I have seen that is not the same, moving props to the list item,
Pass functions as props only with the reference, and invoke the parameters in the child component, or
Pass functions as props with parameters defined, and invoke the function with no parameters in the child
None of the solutions works.
The function invoked are Actions creators of Redux, and dispatched. Is this a issue of Redux or React-Native (maybe ReactJS)
This is a snippet, market as //ERROR the code lines that does'nt work followed by the good ones
class App extends Component {
// On props
// data: an Array
// doThis: an action creator of Redux
// doThat: idem
constructor(){
super();
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
}
render () {
const dataSource = this.ds.cloneWithRows(this.props.data);
return (
<View>
<ListView style={{flex:1}}
dataSource={dataSource}
renderRow={(rowData, sectionID, rowID) =>
<Item rowData={rowData}
//ERROR
//onPress={this.props.doThis}
//onLongPress={this..props.doThat}
//RIGHT NO ERROR TOO
onPress={() => this.props.doThis(rowData)}
onLongPress={() => this.props.doThat(rowData)}
/>
}
/>
</View>
)
}
}
class Item extends Component {
render() {
return (
<View>
<TouchableHighlight
//ERROR
//onPress={() => { this.props.onPress( this.props.rowData ) }}
//onLongPress={() => { this.props.onLongPress( this.props.rowData ) }}
//WRONG TOO
onPress={this.props.onPress}
onLongPress={this.props.onLongPress}
>
<Text>
{rowData}
</Text>
</TouchableHighlight>
</View>
);
}
}
There is a repo with this problem here https://github.com/srlopez/test Thanks in advance
If your high-level callbacks accept a parameter, you need to make sure your anonymous functions accept a parameter as well (Note: creating anonymous functions using the arrow syntax automatically binds our function to the value of this
in the current context). I think you witnessed a combination of issues where either your callbacks were bound to the incorrect context (the window) or you weren't accepting the passed arguments:
class App extends Component {
// On props
// data: an Array
// doThis: an action creator of Redux
// doThat: idem
constructor(){
super();
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
}
render () {
const dataSource = this.ds.cloneWithRows(this.props.data);
return (
<View>
<ListView style={{flex:1}}
dataSource={dataSource}
renderRow={(rowData, sectionID, rowID) =>
<Item rowData={rowData}
onPress={(data) => this.props.doThis(data)}
onLongPress={(data) => this.props.doThat(data)} />
}/>
</View>
)
}
}
class Item extends Component {
render() {
return (
<View>
<TouchableHighlight
onPress={() => this.props.onPress(this.rowData)}
onLongPress={() => this.props.onLongPress(this.rowData)}>
<Text>
{rowData}
</Text>
</TouchableHighlight>
</View>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With