在选择组件中显示和保留值的问题

问题描述 投票:0回答:1

我编写了一个组件,它代表带有一组选项的

select
。选项是从对象中提取的。我的想法是,我想显示一个十字 (
\u{274C}
),而不是 0,并且我还希望能够恢复为空字段。对我来说很重要的是,空字段没有
integer
值。我在 localStorage 中保存一个带有键值对的对象,并检查那里最终有哪些数据。总的来说,我发现了两个我不太明白如何解决的问题:1)当我选择0时,不显示十字。 2) 如果我选择 0,然后尝试返回空值,我会看到 0 保留在 localStorage 中。我那里不需要 0。对我缺少的东西有什么想法吗?”

const SelectField: React.FC<SelectFieldProps> = ({diceOptions, onOptionChange, selectedOptions}) => {
return(
    <div className={Style.container}>
        {diceOptions.map((diceOption: DiceType, index: number) => {
            return (
                <select
                    key={`${diceOption.id}-${index}`}
                    className={Style.select}
                    onChange={(e) => {
                        const value = e.target.value === "" ? "" : Number(e.target.value);
                        onOptionChange(diceOption.id, value);
                    }}
                    value={selectedOptions[diceOption.id][0] || ""}
                >
                    {diceOption.values.map((value: number | "", index: number) => {
                        return (
                            <option key={index} value={value === 0 ? "0" : value}>
                                {value === 0 ? "\u{274C}": value}
                            </option>
                        )
                    })}
                </select>
            )
        })}
    </div>
)
}

从对象中提取选项。

const diceOptions: Array<DiceType> = [
{id: 'One', values: ['', 0, 1, 2, 3, 4, 5]},
{id: 'Two', values: ['', 0, 2, 4, 6, 8, 10]},
{id: 'Three', values: ['', 0, 3, 6, 9, 12, 15]},
{id: 'Four', values: ['', 0, 4, 8, 12, 16, 20]},
{id: 'Five', values: ['', 0, 5, 10, 15, 20, 25]},
{id: 'Six', values: ['', 0, 6, 12, 18, 24, 30]}
];

类型:

export type DiceType = {
id: string,
values: Values[];
}

export type SelectFieldProps = {
diceOptions: DiceType[];
onOptionChange: (id: string, value: number | '') => void;
selectedOptions: {[key: string]: (number | '')[]};
}

export type StateType = Record<string, (number | '')[]>;
export type ActionType = { type: 'clear' | 'replace', id?: string, value?: number | '' };
const App: React.FC = () => {
const [state, dispatch] = useReducer(optionReducer, initialState);

const handleSelectChange = (id: string, value: number | ''):void => {
    dispatch({type: 'replace', id, value });
}

return (
    <>
        <SelectField diceOptions={diceOptions} onOptionChange={handleSelectChange} selectedOptions={state}/>
        <button onClick={() => clearLocalStorage(dispatch)}>Clear storage</button>
    </>


)
}
html reactjs typescript select types
1个回答
0
投票

所以问题出在这一行:

value={selectedOptions[diceOption.id][0] || ""}

每当我的第一个元素是

null, undefined, 0, false
(而
0
只是我的情况)时,它会显示一个空字符串。

© www.soinside.com 2019 - 2024. All rights reserved.