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

React中修改映射生成组件的checked状态问题

问题分析与修复方案

当前代码存在几个核心问题导致选中状态不生效:

  1. 父组件用单个布尔值checkedState管理所有按钮状态,所有按钮会共用同一状态,无法独立控制
  2. ButtonList组件未接收父组件的状态和回调函数,内部直接使用未定义的checkedState和handleChange会报错
  3. Button组件的style语法错误(缺少闭合大括号)

以下分单选和多选两种场景给出修复代码:


场景1:单选(仅能选中一个选项)

父组件Test修改:

export function Test() {
    // 用字符串记录选中的选项value,初始为空
    const [selectedValue, setSelectedValue] = React.useState<string>("");
    
    // 接收选中的选项value,更新状态
    const handleChange = (value: string) => {
        setSelectedValue(value);
    };

    return (
        <View>
            <ButtonList
                options={[
                    { label: "选项1", value: "value" },
                    { label: "选项2", value: "value2" },
                    { label: "选项3", value: "value3" },
                ]}
                value={selectedValue}
                onChange={handleChange}
            />
        </View>
    );
}

ButtonList组件修改:

type Option = {
    label: string;
    value: string;
};

type ButtonListProps = {
    options: Option[];
    value: string;
    onChange: (value: string) => void; // 新增回调属性
};

export function ButtonList({ options, value, onChange }: ButtonListProps) {
    return (
        <View>
            {options.map((option) => (
                <Button
                    // 判断当前选项是否被选中
                    checked={option.value === value}
                    // 点击时传递当前选项的value给父组件
                    onChange={() => onChange(option.value)}
                    key={option.value}
                    label={option.label}
                />
            ))}
        </View>
    );
}

Button组件修改:

type ButtonProps = {
    checked: boolean;
    label?: string;
    onChange?: () => void;
};

export function Button({ checked, label, onChange }: ButtonProps) {
    return (
        <Pressable onPress={onChange}>
            {/* 修复style语法错误,添加默认样式+选中样式 */}
            <View style={{
                padding: 10,
                borderWidth: 1,
                ...(checked && { backgroundColor: "red" })
            }}>
                <Text>{label}</Text>
            </View>
        </Pressable>
    );
}

场景2:多选(可选中多个选项)

父组件Test修改:

export function Test() {
    const options = [
        { label: "选项1", value: "value" },
        { label: "选项2", value: "value2" },
        { label: "选项3", value: "value3" },
    ];
    
    // 初始化选中状态对象,所有选项默认未选中
    const [checkedStates, setCheckedStates] = React.useState<Record<string, boolean>>(
        options.reduce((acc, option) => {
            acc[option.value] = false;
            return acc;
        }, {} as Record<string, boolean>)
    );
    
    // 切换指定选项的选中状态
    const handleChange = (value: string) => {
        setCheckedStates(prev => ({
            ...prev,
            [value]: !prev[value]
        }));
    };

    return (
        <View>
            <ButtonList
                options={options}
                checkedStates={checkedStates}
                onChange={handleChange}
            />
        </View>
    );
}

ButtonList组件修改:

type Option = {
    label: string;
    value: string;
};

type ButtonListProps = {
    options: Option[];
    checkedStates: Record<string, boolean>;
    onChange: (value: string) => void;
};

export function ButtonList({ options, checkedStates, onChange }: ButtonListProps) {
    return (
        <View>
            {options.map((option) => (
                <Button
                    checked={checkedStates[option.value]}
                    onChange={() => onChange(option.value)}
                    key={option.value}
                    label={option.label}
                />
            ))}
        </View>
    );
}

Button组件修改同单选场景的修复代码即可


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 09:45:33