React-Native ListView renderRow传递道具问题。 正确的方式或错误的方式

在React-Native中使用ListView,我已经看到,这是不一样的,移动道具到列表项,

  1. 将函数作为道具传递给引用,并调用子组件中的参数

  2. 将函数传递给定义参数的道具,并在子中调用没有参数的函数

这些解决scheme都不起作用。

被调用的函数是Redux的Actions创build者,并被调度。 这是一个Redux或React-Native(也许是ReactJS)的问题

这是一个片段,市场作为//错误的代码行,没有工作,跟着好的

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> ); } } 

这里有一个回购这个问题https://github.com/srlopez/test在此先感谢

如果你的高级callback接受一个参数,你需要确保你的匿名函数接受一个参数(注意:使用箭头语法创build匿名函数会自动将函数绑定到当前上下文中的值)。 我认为你目睹了以下问题的组合:你的callback被绑定到不正确的上下文(窗口),或者你不接受传递的参数:

 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> ); } } 

这可能是一个问题, this不是在你的closures设置正确。

试试用这种方法来绑定它:

 class Item extends Component { render() { return ( <View> <TouchableHighlight onPress={this.props.onPress.bind(this, this.props.rowData)} onLongPress={this.props.onLongPress.bind(this, this.props.rowData)} > <Text> {rowData} </Text> </TouchableHighlight> </View> ); } }