简体   繁体   中英

How to set initial value in Select tag in React

There is a Select tag, for which I want to have an initial value and set that initial value to variable name , the select tag:

<Field
  name="data.account"
  render={({ field: { name, ...restFieldProps } }) => (
    <Column>
      <Select
        {...restFieldProps}
        value={pl =>
          setFieldValue(name, pl)
        }
        onChange={value => setFieldValue(name, value)}
        placeholder={pl}
        width={300}
        disabled={false}
      >
        <SelectOption value="k1" label="v1" />;
        <SelectOption value="k2" label="v2" />;
      </Select>

    </Column>
  )}
/> 

The problem is, whenever I select something from the drop-down, the variable gets initialized, but not otherwise.

Basically, the onChange is getting called and set the value when I select something from the drop-down list, but it's not getting set when I don't click the drop-down, to handle that I have written the value option in the Select tag, but it's not working.

Could anyone please suggest what might be wrong in this Select tag?

(Note: pl is a variable which is having correct value, verified by adding that in placeholder)

As far as I know, you have to write selected option in SelectOption like this,

<Field
  name="data.account"
  render={({ field: { name, ...restFieldProps } }) => (
    <Column>
      <Select
        {...restFieldProps}
        value={pl =>
          setFieldValue(name, pl)
        }
        onChange={value => setFieldValue(name, value)}
        placeholder={pl}
        width={300}
        disabled={false}
      >
        <SelectOption value="k1" label="v1"  selected={true}/>;
        <SelectOption value="k2" label="v2" />;
      </Select>

    </Column>
  )}
/>

Oh, I see, you mean like this?

something.map(item => 
const isSelected = item === initialValue;
return   <SelectOption value="k1" label="v1"  selected={isSelected}/>;
})

or

something.map(item => 
const isSelected = item === fieldValuee;
return   <SelectOption value="k1" label="v1"  selected={isSelected}/>;
})

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