首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CheckBox in FlatList

CheckBox in FlatList
EN

Stack Overflow用户
提问于 2019-09-08 07:32:42
回答 1查看 1.2K关注 0票数 2

我想向用户提供一个可供选择的项目列表。项目是从一个Redux获取的。这是设备上联系人的列表。

我使用了来自React的"FlatList",以及来自React的"ListItem"。ListItem有一个CheckBox.

让用户选中/取消选中列表中的项目,他/她可以单击CheckBox或ListItem.的任何部分。

我的第一次尝试:,如您在下面的代码中所看到的,我必须复制代码的一部分才能实现这一点。是否有更明智的方法来做到这一点(避免代码重复)?

代码语言:javascript
复制
<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);
                },
            }}
        />
    );
};

我的第二次尝试:,我尝试使用一个函数。我得到了错误消息(最大更新深度超过了)。

代码语言:javascript
复制
<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);
};

谢谢你的努力和时间来帮助..。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-08 15:06:28

请更改此代码

代码语言:javascript
复制
<ListItem
        ..
            onPress={_onPress(index)}

            checkBox={{
                ..
                onPress: _onPress(index),
            }}
        />

代码语言:javascript
复制
<ListItem
        ..
            onPress={() =>_onPress(index)}

            checkBox={{
                ..
                onPress:() => _onPress(index),
            }}
        />

onPress={_onPress(索引)}将立即调用函数

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57839977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档