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

使用react-native-calendars的Agenda组件如何单独修改每个条目复选框颜色

问题根因

你全局共用了同一个toggleColor状态控制所有条目的复选框颜色,所有条目都绑定了同一个状态变量,自然修改一个会触发所有条目同步变更。


完整修改方案

1. 移除无用状态,调整条目初始化逻辑

首先删除state中的toggleColor字段,然后在loadItems方法生成条目时,给每个条目增加独立的选中状态属性:

// 修改loadItems内的item生成逻辑
this.state.items[strTime].push({
    id: `${strTime}-${j}`, // 可选:新增唯一标识,避免名称重复导致匹配错误
    name: 'Item for ' + strTime + ' #' + j,
    height: Math.max(50, Math.floor(Math.random() * 150)),
    checked: false // 新增独立选中状态
});

2. 重写复选框状态变更方法

替换原来的changeCheckBox方法,仅修改当前点击条目的选中状态:

changeCheckBox(dateStr, itemId) {
    const newItems = {...this.state.items};
    // 找到对应条目翻转选中状态
    const targetIndex = newItems[dateStr].findIndex(item => item.id === itemId);
    newItems[dateStr][targetIndex].checked = !newItems[dateStr][targetIndex].checked;
    this.setState({items: newItems});
}

3. 调整renderItem逻辑

使用条目自身的checked属性控制复选框颜色,点击时传递对应条目的定位参数:

renderItem(item, date) {
    const checkBoxColor = item.checked ? "#F56868FF" : "white";
    return (
        <View style={styles.item} onPress={() => Alert.alert(item.name)}>
            <View>
                <Text>{item.name}</Text>
            </View>
            <TouchableOpacity
                onPress={() => this.changeCheckBox(date.dateString, item.id)}
                style={{
                    borderWidth: 0.5,
                    width: 20,
                    height: 20,
                    borderRadius: 10,
                    marginLeft: 250,
                    justifyContent: 'center',
                    alignContent: 'center',
                    marginTop: -5,
                    backgroundColor: checkBoxColor
                }}/>
        </View>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:57:02