【问题标题】:React-select defaultValue is not showingReact-select defaultValue 未显示
【发布时间】:2021-10-22 02:01:37
【问题描述】:

我正在使用 Formik 和 React-select 库,而 defaultValue 没有工作/生效,它仍然是空的,我不知道为什么会这样。

MySelectInput 组件:

interface Props {
    // .. other props
    options: CategoryOptions[];
    defaultCategory: CategoryOptions;
}

const MySelectInput: React.FC<Props> = (props) => {
    const [field, meta, helpers] = useField(props.name);
    
    return (
        <>
            <Select
                options={props.options}
                isSearchable
                defaultValue={props.defaultCategory}
                onChange={(v) => helpers.setValue(v!.value)}
                onBlur={() => helpers.setTouched(true)}
                placeholder={props.placeholder}
                styles={customSelectStyles}
            />
        </>
    )
};

export default MySelectInput;

用法:

<MySelectInput
   options={CategoryOptions}
   placeholder="Category"
   name="category"
   label="Category"
   defaultCategory={{ value: activity.category, label: activity.category }}
/>

我的对象数组(CategoryOptions):

export const CategoryOptions: CategoryOptions[] = [
    { value: 'drinks', label: 'Drinks' },
    { value: 'music', label: 'Music' },
    { value: 'travel', label: 'Travel' },
];

选项工作正常且显示良好,但 defaultValue 不工作。如果我在对象属性中使用静态字符串,例如:

defaultCategory={{ value: "test", label: "test" }}

运行良好。有什么想法吗?

【问题讨论】:

    标签: reactjs select formik react-select


    【解决方案1】:

    我认为您应该使用 CategoryOptions 中的项目。

    而不是

    defaultValue={props.defaultCategory}
    

    defaultValue={props.defaultCategory[0]}
    

    我还想知道为什么您的 CategoryOptions 对象与 CategoryOptions 类型相同。也许你应该把它重命名为categoryOptions

    【讨论】:

    • 这不起作用,因为我将 defaultCategory 类型设置为对象而不是对象数组,我将对象作为道具而不是数组传递,CategoryObject 的类型为export interface CategoryOptions { value: string; label: string; } 我不明白你的问题好吗?
    猜你喜欢
    • 2021-07-11
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多