Highlight a selected item in React-Native FlatList

时间秒杀一切 提交于 2019-12-08 14:42:12

问题


I put together a simple React-native application to gets data from a remote service, loads it in a FlatList. When a user taps on an item, it should be highlighted and selection should be retained. I am sure such a trivial operation should not be difficult. I am not sure what I am missing.

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  ActivityIndicator,
  Image,
  TouchableOpacity,
} from 'react-native';

export default class BasicFlatList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      data: [],
      page: 1,
      seed: 1,
      error: null,
      refreshing: false,
      selectedItem:'null',
    };
  }

  componentDidMount() {
    this.makeRemoteRequest();
  }

  makeRemoteRequest = () => {
    const {page, seed} = this.state;
    const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
    this.setState({loading: true});
    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: page === 1 ? res.results : [...this.state.data, ...res.results],
          error: res.error || null,
          loading: false,
          refreshing: false
        });
      })
      .catch(error => {
        this.setState({error, loading: false});
      });
  };

  onPressAction = (rowItem) => {
    console.log('ListItem was selected');
    console.dir(rowItem);
    this.setState({
      selectedItem: rowItem.id.value
    });
  }

  renderRow = (item) => {
    const isSelectedUser = this.state.selectedItem === item.id.value;
    console.log(`Rendered item - ${item.id.value} for ${isSelectedUser}`);
    const viewStyle = isSelectedUser ? styles.selectedButton : styles.normalButton;
    return(
        <TouchableOpacity style={viewStyle} onPress={() => this.onPressAction(item)} underlayColor='#dddddd'>
          <View style={styles.listItemContainer}>
            <View>
              <Image source={{ uri: item.picture.large}} style={styles.photo} />
            </View>
            <View style={{flexDirection: 'column'}}>
              <View style={{flexDirection: 'row', alignItems: 'flex-start',}}>
                {isSelectedUser ?
                  <Text style={styles.selectedText}>{item.name.first} {item.name.last}</Text>
                  : <Text style={styles.text}>{item.name.first} {item.name.last}</Text>
                }
              </View>
              <View style={{flexDirection: 'row', alignItems: 'flex-start',}}>
                <Text style={styles.text}>{item.email}</Text>
              </View>
            </View>
          </View>
        </TouchableOpacity>
    );
  }

  render() {
    return(
      <FlatList style={styles.container}
        data={this.state.data}
        renderItem={({ item }) => (
          this.renderRow(item)
        )}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
  },
  selectedButton: {
    backgroundColor: 'lightgray',
  },
  normalButton: {
    backgroundColor: 'white',
  },
  listItemContainer: {
    flex: 1,
    padding: 12,
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  text: {
    marginLeft: 12,
    fontSize: 16,
  },
  selectedText: {
    marginLeft: 12,
    fontSize: 20,
  },
  photo: {
    height: 40,
    width: 40,
    borderRadius: 20,
  },
});

When user taps on an item in the list, "onPress" method is invoked with the information on selected item. But the next step of highlight item in Flatlist does not happen. 'UnderlayColor' is of no help either.

Any help/advice will be much appreciated.


回答1:


In place of this.state.selectedItem and setting with/checking for a rowItem.id.value, I would recommend using a Map object with key:value pairs as shown in the RN FlatList docs example: https://facebook.github.io/react-native/docs/flatlist.html. Take a look at the js Map docs as well: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map.

The extraData prop recommended by @j.I-V will ensure re-rendering occurs when this.state.selected changes on selection.

Your onPressAction will obviously change a bit from example below depending on if you want to limit the number of selections at any given time or not allow user to toggle selection, etc.

Additionally, though not necessary by any means, I like to use another class or pure component for the renderItem component; ends up looking something like the following:

export default class BasicFlatList extends Component {
  state = {
    otherStateStuff: ...,
    selected: (new Map(): Map<string, boolean>) //iterable object with string:boolean key:value pairs
  }

  onPressAction = (key: string) => {
    this.setState((state) => {
      //create new Map object, maintaining state immutability
      const selected = new Map(state.selected);
      //remove key if selected, add key if not selected
      this.state.selected.has(key) ? selected.delete(key, !selected.get(key)) : selected.set(key, !selected.get(key));
      return {selected};
    });
  }

  renderRow = (item) => {
    return (
        <RowItem
          {...otherProps}
          item={item}
          onPressItem={this.onPressAction}
          selected={!!this.state.selected.get(item.key)} />
    );
  }

  render() {
    return(
      <FlatList style={styles.container}
        data={this.state.data}
        renderItem={({ item }) => (
          this.renderRow(item)
        )}
        extraData={this.state}
      />
    );
  }
}


class RowItem extends Component {
  render(){
    //render styles and components conditionally using this.props.selected ? _ : _
    
    return (
      <TouchableOpacity onPress={this.props.onPressItem}>
        ...
      </TouchableOpacity>
    )
  }
}



回答2:


You should pass an extraData prop to your FlatList so that it will rerender your items based on your selection

Here :

<FlatList style={styles.container}
    data={this.state.data}
    extraData={this.state.selectedItem}
    renderItem={({ item }) => (
      this.renderRow(item)
    )}
 />

Source : https://facebook.github.io/react-native/docs/flatlist

Make sure that everything your renderItem function depends on is passed as a prop (e.g. extraData) that is not === after updates, otherwise your UI may not update on changes




回答3:


You can do something like:

  1. Create a ref for your FlatList;
  2. For the renderItem, use something like a TouchableOpacity with an onPress event passing the index of the renderItem, each item of your array should have an index as below:

    const CategoryList = [ {name: "a name", index: 0}, .... ]

  3. Create a variable to control the state of the component:

    this.state = { selected_category: ' '}

  4. The function to change the state created above:

    _handleCategorySelect = (index) => { this.setState({selected_category: index}); }

the FlatList:

<FlatList
   data={CategoryList}
   ref={(e) => this.categoryList = e}
   renderItem={(category) => 
      <TouchableOpacity 
        onPress={() => this._handleCategorySelect(category.item.index)}
        style={this.state.selected_category === category.item.index ?  
                 styles.selected : null}
      >
         <Text>{category.item.name}</Text>
      </TouchableOpacity>
   }
/>
  1. Make a style for the selected item and that's it!


来源:https://stackoverflow.com/questions/46686365/highlight-a-selected-item-in-react-native-flatlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!