React-Native ListView renderRow发出传递道具.正确的方式或错误的方式

San*_*nti 7 android ios reactjs react-native redux

在React-Native中使用ListView,我看到不一样,将props移动到列表项,

  1. 仅使用引用将函数作为props传递,并调用子组件中的参数,或

  2. 将函数作为带有参数定义的props传递,并调用子函数中没有参数的函数

没有一个解决方案有效.

调用的函数是Redux的Actions创建者,并被调度.这是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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Mot*_*Azu 0

this这可能是你的关闭设置不正确的问题。

尝试这样绑定它:

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)