React Native:更改ListView项目的样式 [英] React native: change style of ListView item on touch

查看:52
本文介绍了React Native:更改ListView项目的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to update the style of a ListView item when that item is pressed so that the enduser is aware that he/she selected an item.

列表视图:

<ListView
    dataSource={this.state.dataSource}
    renderRow={this.renderFriend}
/>

行渲染器:

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

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

How could I change the style of the second View when the user activates the TouchableHighlight?

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

I would also like to add the selected object to an array of selected objects.

推荐答案

TouchableHighlight 时,应使用组件状态并在其中存储选定的好友ID.

You should use the component state and store the selected friends ids in it when pressing the 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>
  );
}

这篇关于React Native:更改ListView项目的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆