简体   繁体   中英

react-select default value set but not highlighted

When I set the defaultValue in the react-select Component, it is correctly recognised and set, but is not highlighted in the select menu.

<Select onChange={handleChange} options={options} styles={styles} defaultValue={defaultValue} />

defaultValue selected

Not highlighted in the menu

This is the defaultValue, and it's correct:

{
    "value": {
        "param_user": "TEST"
    },
    "label": "TEST"
}

Perhaps it is because the value is an object?

Does anyone have any suggestions?

You are correct, the problem arrises because the default implementation of react-select checks whether the option is selected by reference. This means that if your default option does not come from the options array itself, it will not display as selected. Fortunately, the react-select library allows you to pass in a predicate that determines whether an option is selected. In your case:

const isOptionSelected = (option, selectValue) => selectValue.some(
  (val) => val.value.param_user === option.value.param_user
);
<Select isOptionSelected={isOptionSelected} onChange={handleChange} options={options} styles={styles} defaultValue={defaultValue} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM