在react-native中更新FlatList的特定行

时间:2017-10-09 21:07:19

标签: react-native react-navigation react-native-flatlist

我正在使用FlatList加载一些记录。在FlatList上面我有一个按钮,当我点击这个按钮时,FlatList中加载了11230个项目,我想要的是使用onpress更新特定行背景颜色和flatlist项目的图像

   import React, { Component } from 'react';
   import {
     AppRegistry,
     StyleSheet,
     Text,
     View,
     FlatList,
     TouchableOpacity,
     TextInput,
     TouchableWithoutFeedback,
     Image 
   } from 'react-native'; // Impoert required components

   const GLOBAL_DATA = [];//To store json data
   const PER_PAGE = 10;
   const paginateArray = (array, pageSize, pageNumber) => {
     const _pageNumber = pageNumber - 1;
     return array.slice(_pageNumber * pageSize, (_pageNumber + 1) * pageSize);
   };

   for (let i = 0; i <= 100000; i++) {
     GLOBAL_DATA.push({
       key: i,
       produto: {
         descricao: 'Item number ' + i,
       }
     });
   }

   export default class flatlistdemo extends Component {
     constructor(props) {
       super(props);          
       this.state = {
         type: 'default',
         data: [],
         page: 1,
       };
     }

     componentDidMount() {
       this.setState({
         data: paginateArray(GLOBAL_DATA, PER_PAGE, this.state.page),
       });
     }

     getPagedOffers = () => {
       this.setState((state) => ({
         data: state.data.concat( paginateArray(GLOBAL_DATA, PER_PAGE, this.state.page) ),
       }));
     }

     handleLoadMore = () => {
       this.setState({
        page: this.state.page + 1,
       },
       () => {
         this.getPagedOffers();
        }
       );
     }

     render() {
       return (
         <View style={styles.container}>
           <FlatList
             data={this.state.data}
             onEndReached={this.handleLoadMore}
             onEndReachedThreshold={50}
             getItemLayout={(data, index) => (
               {length: 40, offset: 40 * index, index}
             )}
             renderItem={this._renderItem}
           />       
         </View>
       );
     }

     _renderItem = ({item}) => (
       <MyListItem
         produto={item.produto}
       />
     );
     }

     class MyListItem extends React.PureComponent {
       render() {
         return (
          <View 
            style={{
              paddingVertical: 10,
              backgroundColor:"#321AFE"
          }}>
            <TouchableOpacity onPress={() => this.updateRow(this.props.produto)}>
              <Text 
                style={{
                  color: '#000', 
                  height: 40,
                  justifyContent: 'center'
              }}>
                  {this.props.produto.descricao}
              </Text>
              <Image uri={{xyz}}
            </TouchableOpacity>
          </View>
         )
        }

       updateRow(item){
       //Here i want to update item of flatlist with new image and background color
       }
       }
       //Styles used for page
       const styles = StyleSheet.create({
          container: {
            marginTop: 30,
            alignItems: 'center',
          },
       });

       AppRegistry.registerComponent('flatlistdemo', () => flatlistdemo);

如何使用映射功能更新flatlist行,以及如何使用导航导航到其他屏幕 目前在导航方面面临问题 无法读取未定义的属性“导航”

this.props.navigation.navigate("Home", UserID);

1 个答案:

答案 0 :(得分:0)

你可以使用flatlist的选定道具来实现这个目标(可能是)

你的构造函数应初始化所选

的空状态
constructor(props){
   super(props)
   this.state={
     slected:{}
   }
}

你的渲染功能应该如下所示

render(){
     <FlatList
              data={YOUR_DATA}
              removeClippedSubviews={false}
              keyExtractor={(item, index) => item.key}
              renderItem={this.renderItem.bind(this)}
              selected={this.state.selected} />
}

你的renderItem函数应该如下所示

renderItem= ({ item, index }) =>{
    let {selected } = this.state;
    let isSelected = !!selected[item.key]; // renderItem depends on state


    return (
     <View>
        {isSelected?
         <Text>Yes, I am Selected row</Text>:
         <Text>Please select me</Text>}
     </View>
    );
}

您更新所选

的功能
updateSelected =(isSingleSelected = false, rowsToUpdate = ARRAY OF ROWS NEED BE SELECTED)=>{
    if(isSingleSelected){
         let item = rowsToUpdate[0];
         this.setState((prevState)=>{
              let {prevSelected} = prevState;
              return {
                   selected:{[item.key]:!prevSelected[item.key]} //just toggle the state of current item
              }
         }
    }else{
       items = rowsToUpdate[0];
       this.setState((prevState)=>{
           let {prevSelected} = prevState;
           let objUpdating={}
           for(let i =0; i< items.length; i++){
               let item = items[i];
               objUpdating = {...objUpdating,[item.key]:!objUpdating[item.key]}        //using spread operator to avoid mutation you can try concat
           }
          return {
               selected:{...prevSelected, ...objUpdating} //matching keys will be overwritten
          }
       }
    }
}
  

试试这个并告诉我们这是否适合您

     

可以有更好的解决方案,请添加您的解决方案,因为我也在寻找更好的实施方案