RN元素:绑定列表onpress

时间:2017-05-02 08:25:19

标签: react-native

React Native相对较新;在下面的示例代码中,我想创建一个带有绑定onPress函数的列表。不幸的是,按下一个项目将始终打印最后一个项目,这是" Suze"在这种情况下。

import { List, ListItem } from 'react-native-elements';
...

onPress(name){
  console.log(name);
}

renderPerson(person) {
  return (< ListItem
    key={person._id}
    title={person.name}
    onPress={() => this.onPress(person.name)}
  />)
}


renderPeople = () => {
  people =  [{"_id": 1, "name": "Eric"},
             {"_id":2, "name": "Paul"},
             {"_id":3, "name": "Suze"}]
  return people.map((p) => (
    this.renderPerson(p)
  ))
}

render() {
  return (
    <List>
      {this.renderPeople()}
    </List>
  )
}

更新

包含的构造函数:

constructor(props) {
  super(props);
  this.renderPerson = this.renderPerson.bind(this);
  this.renderPeople = this.renderPeople.bind(this);
}

但仍打印最后一项

1 个答案:

答案 0 :(得分:0)

试过你的例子,它按预期工作,所以你必须遗漏你粘贴的代码中的某些内容。

话虽如此,为了便于阅读,我会这样写:

  constructor(props) {
    super(props);
    this.renderPerson = this.renderPerson.bind(this);
    this.renderPeople = this.renderPeople.bind(this);
  }

  renderPerson(person) {
    return (<ListItem
      key={person._id}
      title={person.name}
      onPress={() => this.onPress(person.name)}
    />);
  }

  onPress(name) {
    console.log(name);
  }

  renderPeople(people) {
    return people.map((p) => this.renderPerson(p));
  }

  render() {
    const people =  [{"_id": 1, "name": "Eric"},
               {"_id":2, "name": "Paul"},
               {"_id":3, "name": "Suze"}];
    return (
      <View style={{flex: 1}}>
        <List>
          {this.renderPeople(people)}
        </List>
      </View>
    );
  }