我想向用户提供一个可供选择的项目列表。项目是从一个Redux获取的。这是设备上联系人的列表。
我使用了来自React的"FlatList",以及来自React的"ListItem"。ListItem有一个CheckBox.
让用户选中/取消选中列表中的项目,他/她可以单击CheckBox或ListItem.的任何部分。
我的第一次尝试:,如您在下面的代码中所看到的,我必须复制代码的一部分才能实现这一点。是否有更明智的方法来做到这一点(避免代码重复)?
<FlatList
keyExtractor={(item, index) => index.toString()}
data={props.contactList}
renderItem={_renderItem}
ListEmptyComponent={<Text>There are no contacts to show.</Text>}
refreshing={state.refreshing}
onRefresh={_onRefresh}
/>
const _renderItem = ({ item, index }) => {
return (
<ListItem
title={item.name}
onPress={() => {
// The following 2 statements are repeated (below)!!!
_toggleCheck(index);
props.acContactSelect(index);
}}
checkBox={{
checked: _isItemChecked(index),
checkedIcon: "check",
onPress: () => {
// The following 2 statements are repeated (above)!!!
_toggleCheck(index);
props.acContactSelect(index);
},
}}
/>
);
};我的第二次尝试:,我尝试使用一个函数。我得到了错误消息(最大更新深度超过了)。
<FlatList
.. {similar to the code above}
/>
const _renderItem = ({ item, index }) => {
return (
<ListItem
..
onPress={_onPress(index)}
checkBox={{
..
onPress: _onPress(index),
}}
/>
);
};
const _onPress = (index) => {
_toggleCheck(index);
props.acContactSelect(index);
};谢谢你的努力和时间来帮助..。
发布于 2019-09-08 15:06:28
请更改此代码
<ListItem
..
onPress={_onPress(index)}
checkBox={{
..
onPress: _onPress(index),
}}
/>到
<ListItem
..
onPress={() =>_onPress(index)}
checkBox={{
..
onPress:() => _onPress(index),
}}
/>onPress={_onPress(索引)}将立即调用函数
https://stackoverflow.com/questions/57839977
复制相似问题