react-native - FlatList 中的复选框
问题描述
我想向用户展示一个可供选择的项目列表。这些项目来自 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);
};
感谢您的努力和时间来帮助...
解决方案
请更改此代码
<ListItem
..
onPress={_onPress(index)}
checkBox={{
..
onPress: _onPress(index),
}}
/>
至
<ListItem
..
onPress={() =>_onPress(index)}
checkBox={{
..
onPress:() => _onPress(index),
}}
/>
onPress={_onPress(index)} 将立即调用函数
推荐阅读
- javascript - 我已经使用 React 构建了一个购物车。为什么我的购物车不工作?通过工作,我的意思是为什么购物车中的数量没有增加?
- flutter - 如何从http响应中提取标头值?
- python - 将函数应用于熊猫数据框时出现KeyError
- c# - 如何在 C# 运行时向对象添加属性?
- python - 如何在 C# WFA 中将 Python 脚本附加到 ToolStripMenuItem?
- bash - 在 Mac 上检测音频输出?
- python - 将字符串分成对
- python - python中循环的十进制增量
- ag-grid - Ag-Grid - 如何在表启动后取消设置 gridOptions 函数
- fortran - Fortran 66 if() 转到