我想向用户展示一个可供选择的项目列表。这些项目来自 Redux 状态对象。它是设备上的联系人列表。
我使用了来自 React-Native的“FlatList”和来自 React-Native-Elements的“ListItem” 。ListItem 有一个复选框。
为了让用户选中/取消选中列表中的项目,他/她可以单击 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);
};
感谢您的努力和时间来帮助...