React native:触摸时更改ListView项的样式

Phi*_*aes 4 javascript android listview reactjs react-native

我想在按下该项时更新ListView项的样式,以便最终用户知道他/她选择了一个项.

列表显示:

<ListView
    dataSource={this.state.dataSource}
    renderRow={this.renderFriend}
/>
Run Code Online (Sandbox Code Playgroud)

行渲染器:

renderFriend(friend) {
  return (
    <TouchableHighlight onPress={ ??? }>
      <View style={styles.friendItem}>
        <View style={styles.profilePictureContainerNoBorder}>
          <Image
            source={{uri: 'https://graph.facebook.com/' + friend.id + '/picture?width=500&height=500'}}
            style={styles.profilePicture}
          />
        </View>
        <Text style={styles.profileName}>{friend.name}</Text>
      </View>
    </TouchableHighlight>
  );
}
Run Code Online (Sandbox Code Playgroud)

当用户激活TouchableHighlight时,如何更改第二个视图的样式?

我还想将所选对象添加到所选对象的数组中.

Alm*_*uro 6

您应该使用组件状态,并在按下时将所选的朋友ID存储在其中TouchableHighlight.

就像是:

constructor(props) {
  super(props);
  this.state = {
    selectedFriendIds: [],
  }
}

selectFriend(friend) {
  this.setState({
    selectedFriendIds: this.state.selectedFriendIds.concat([friend.id]),
  });
}

renderFriend(friend) {
  const isFriendSelected = this.state.selectedFriendIds.indexOf(friend.id) !== -1;
  const viewStyle = isFriendSelected ?
    styles.profilePictureContainerSelected : styles.profilePictureContainerNoBorder;

  return (
    <TouchableHighlight onPress={ () => this.selectFriend(friend) }>
      <View style={styles.friendItem}>
        <View style={viewStyle}>
          <Image
            source={{uri: 'https://graph.facebook.com/' + friend.id + '/picture?width=500&height=500'}}
            style={styles.profilePicture}
          />
        </View>
        <Text style={styles.profileName}>{friend.name}</Text>
      </View>
    </TouchableHighlight>
  );
}
Run Code Online (Sandbox Code Playgroud)