简体   繁体   English

React Native 更新一个平面列表项

[英]React Native Update a Flatlist Item

I want to update a specific Flatlist row when it is clicked, how can I do this?我想在单击时更新特定的 Flatlist 行,我该怎么做? The solutions I found are all using extraData={this.state} , which is not working in my code.我找到的解决方案都在使用extraData={this.state} ,这在我的代码中不起作用。

const [records,setRecords] = useState([]);
//add initial data to records
...
return (
<FlatList
    data={records}
    keyExtractor={item => item.id}
    renderItem={itemData =>
        <RecordItem
            onSelect={() => {
                props.navigation.navigate({...})
                }
            } 
            onApply={()=>{
                // in my RecordItem these is a button to call onApply(), 
                and I want to update the Flatlist when I click this button

                var res = applyHandler();
                return res;
            }}
        >
        </RecordItem>
     }
/>)

To update your flatlist item, you just have to update the data it is rendering from, in order to do this, in your onApply function you know the item index with which you can update the record index like:要更新您的平面列表项目,您只需更新它正在呈现的数据,为此,在您的onApply function 中,您知道可以更新记录索引的项目索引,例如:

const [records,setRecords] = useState([]);
//add initial data to records
...
return (
<FlatList
    data={records}
    keyExtractor={item => item.id}
    renderItem={itemData =>
        <RecordItem
            onSelect={() => {
                props.navigation.navigate({...})
                }
            } 
            onApply={()=>{
                // here you will get reference to record item index, 
                const itemIndex = itemData.index;
                const modRecords = [...records];
                modRecords[itemIndex].title = 'NEW TITLE';
                // assuming title is what you want to change
                // now just update the records using setRecords
                setRecords(modRecords);
            }}
        >
        </RecordItem>
     }
/>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM