You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中@react-native-community/checkbox无法取消勾选问题求助

问题原因

  • isChecked 函数没有添加return语句,执行后永远返回undefined,CheckBox组件无法拿到正确的勾选状态,所以会出现状态更新后视图不跟随变化的问题。
  • 状态更新直接依赖当前的checkList变量,在列表渲染的回调场景下容易触发闭包陷阱,拿到过期的旧状态,导致更新异常。
  • 原代码还缺失了useState的导入语句,也可能引发运行报错。

修复方案

完整修复后的代码如下:

import { useState } from 'react';
import CheckBox from '@react-native-community/checkbox';
import { useRoute, useNavigation } from '@react-navigation/native';

export const ActionsScreen = () => {
  const route = useRoute<ActionScreenRouteProp>();
  const params = route.params;
  const { actionList, eventType, emergencyRole } = params
  const [checkList, setCheckList] = useState<any[]>(actionList.map(e => ({ key: e.key, checked: false })));
  // 补全return语句,用find替代filter优化查询性能,同时添加兼容逻辑避免匹配不到key时报错
  const isChecked = (key) => {
    return checkList.find(e => e.key == key)?.checked ?? false
  }

  const renderActionItem = ({ item, index }) => {
    return (
      <TouchableOpacity
        key={index}
        activeOpacity={.7}
        style={styles.touchableOpacity}
        onPress={() => { console.log(item) }}
      >
        <CheckBox
          style={styles.checkBox}
          tintColors={{ true: 'white', false: 'white' }}
          value={isChecked(item.key)}
          // 改用函数式更新获取最新状态,避免闭包导致的状态更新异常
          onValueChange={() => {
            setCheckList(prev => prev.map(e => {
              if (e.key == item.key) {
                return {...e, checked: !e.checked}
              }
              return e
            }))
          }}
        />
        <Text style={styles.labelText}>{`${item.sequenceID}. ${item.label}`}</Text>
      </TouchableOpacity>
    )
  }

  return (
      <SafeAreaView style={styles.container}>
        <FlatList
          style={styles.flatListView}
          data={actionList}
          keyExtractor={(item, index) => index.toString()}
          renderItem={renderActionItem}
          
        />
      </SafeAreaView>
  );
}

内容的提问来源于stack exchange,提问作者emma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 21:15:03