如何在React-Select中设置默认值

185

我在使用react-select时遇到了问题。我使用redux form,而且我已经使我的react-select组件与redux form兼容。以下是代码:

const MySelect = props => (
    <Select
        {...props}
        value={props.input.value}
        onChange={value => props.input.onChange(value)}
        onBlur={() => props.input.onBlur(props.input.value)}
        options={props.options}
        placeholder={props.placeholder}
        selectedValue={props.selectedValue}
    />
);

这是我如何渲染它:

<div className="select-box__container">
    <Field
    id="side"
    name="side"
    component={SelectInput}
    options={sideOptions}
    clearable={false}
    placeholder="Select Side"
    selectedValue={label: 'Any', value: 'Any'}
    />
</div>

但问题是我的下拉列表没有我想要的默认值。我做错了什么?有什么想法吗?


这是正确的:value={props.input.value}。你遇到了什么问题? - Ved
2
我的问题是,我希望在首次渲染时为我的选择设置一个defaultValue,但我无法实现。 - RamAlx
1
当它首次渲染时,props.input.value的值是多少? - Ved
这是我的问题。如何设置默认值? - RamAlx
你想要什么值? - Ved
我想要一个默认值为“任何”的值。 - RamAlx
27个回答

0
import { useTheme } from 'next-themes';
import { find } from 'lodash';

const ProductSelect = ({
  loading,
  options,
  onSelect,
  value,
  handleChange,
  ...props
}) => {
  const findDefaultValueById = find(options, { value });

  if (value && !findDefaultValueById) {
    return 'Loading...';
  }

  const { theme } = useTheme();
  const isDarkMode = theme === 'light';
  const backgroundColor = !isDarkMode ? '#18181b' : 'white';
  const borderColor = !isDarkMode ? '#3f3f46' : '#d4d4d8';
  const textColor = !isDarkMode ? 'white' : '#18181b';
  const placeholderColor = !isDarkMode ? '#fff' : '#18181b';
  const selectedValueColor = !isDarkMode ? 'white' : '#18181b';

  const handleSelect = (selectedValue) => {
    if (selectedValue && onSelect) {
      onSelect(selectedValue.id || null);
    } else if (!selectedValue) {
      onSelect(null);
    }
  };

  return (
    <div className="z-50 relative">
      <AsyncSelect
        className={`bg-${backgroundColor} ${
          isDarkMode ? 'dark:bg-[#18181b]' : ''
        } w-full outline-none min-h-unit-12 rounded-large transition-colors motion-reduce:transition-none`}
        styles={{
          control: (baseStyles) => ({
            ...baseStyles,
            borderColor,
            backgroundColor: `bg-${backgroundColor}`,
            color: `!text-${textColor}`,
            fontSize: 'font-medium',
            boxShadow: 'none',
            paddingTop: 12,
            paddingBottom: 12,
            borderRadius: 14,
            borderWidth: 2,
          }),
          menu: (provided) => ({
            ...provided,
            backgroundColor,
            borderRadius: 12,
          }),
          option: (styles, { isFocused }) => ({
            ...styles,
            backgroundColor: isFocused ? borderColor : backgroundColor,
            color: isFocused ? textColor : textColor,
            borderRadius: 12,
            fontSize: 14,
          }),
          singleValue: (styles) => ({
            ...styles,
            borderRadius: 12,
            fontSize: 14,
            color: selectedValueColor,
          }),
          menuList: (styles) => ({
            ...styles,
            borderRadius: 12,
            paddingLeft: 12,
            paddingRight: 12,
          }),
          placeholder: (styles) => ({
            ...styles,
            color: placeholderColor,
          }),
        }}
        isClearable
        cacheOptions
        defaultOptions
        options={options}
        isLoading={loading}
        noOptionsMessage={() => (loading ? 'Loading...' : 'No options found')}
        loadingMessage={() => 'Searching...'}
        onChange={handleSelect}
        defaultValue={findDefaultValueById}
        {...props}
      />
    </div>
  );
};

export default ProductSelect;

// USING. //

<ProductSelect
            loading={productsLoading}
            label="Product and code"
            ariaLabel="Product"
            name="profile.product"
            placeholder="Product"
            value={values.profile.product}
            onSelect={(product) => setFieldValue('profile.product', product)}
            options={allProducts}
            initialValues={values?.profile.product}
            handleChange={handleChange}
            error={
              errors && errors?.profile?.product && touched?.profile?.product
                ? errors?.profile?.product
                : undefined
            }
          />

0
    <select onChange={handleCountry} value={selectCountry}>
-------------------add this field----------------
          <option value="" disabled>
            Select a country
          </option>
-------------------add this field----------------          
         {data?.continent?.countries.map(({ name, code }) => (
            <option key={code} value={code}>
              {name}
            </option>
          ))}
        </select>

-1

2022 年的例子,使用Redux react和useSelector

从 2022 年开始,在react-select 中有一个 defaultValue 选项。请注意,如果您正在使用 getOptionLabel 和 getOptionValue,则需要使您的默认值与您设置的这些选项参数匹配...

例如


const responder = useSelector((state) => state.responder)



<Select
              name="keyword"
              required={true}
              className="mb-3"
              styles={customStyles}
              components={animatedComponents}
              closeMenuOnSelect={true}
              options={keywords}
              defaultValue={responder ? responder[0]?.responder?.keyword?.map((el) => { return {title: el.title, _id: el._id}}): ""}
              getOptionLabel={({title}) => title}
              getOptionValue={({_id}) => _id}
              onChange={(_id) => setUpload({...upload, keyword: _id})}
              isMulti
              placeholder="select Keywords"
              isSearchable={true}
              errors={errors}
              innerRef={register({
                required: "Add your Keyword"
              })}
            />


与其使用{label: "this", value: "that}设置您的默认值

我需要使用defaultValue({title:"this", _id: "that"})来设置我的默认值


-1
<Input 
  type='select' 
   name='defaultproperty'
   id='propertyselect'      
    >  
                         <option 
                          key={id} 
                          value={item.propertyId}
                          id = {item.propertyName}
                          defaultValue = {orgPropertyId} 
                          selected={item.propertyId === orgPropertyId}
                         >
                          {item.propertyName}
                           </option>  
                ) 
            </Input>

使用选定的内容作为默认值文本。


-1

我认为你可以在标签中使用selected属性

         <select
            defaultValue={plan.name}
            className="select w-full max-w-xs text-gray-700 mt-4"
          >
            {plans.vps.map((i) => (
              <option
                selected={plan.name == i.name}
                key={i.name}
                className="p-2 border"
                value={i.name}
              >
                {i.name}
              </option>
            ))}
          </select>

看这个 selected={plan.name == i.name} 还要注意值的更新 defaultValue={plan.name}


-2
在 react-select 中,如果你想为自定义标签定义,可以尝试这个方法。
  <Select
    getOptionLabel={({ name }) => name}
  />

-3
您可以简单地这样做:
在react-select中,初始选项值
const optionsAB = [
  { value: '1', label: 'Football' },
  { value: '2', label: 'Cricket' },
  { value: '3', label: 'Tenis' }
];

仅提供API:

apiData = [
  { games: '1', name: 'Football', City: 'Kolkata' },
  { games: '2', name: 'Cricket', City: 'Delhi' },
  { games: '3', name: 'Tenis', City: 'Sikkim' }
];

在 react-select 中,对于 defaultValue=[{value: 1, label: Hi}]。可以像下面这个例子一样使用 defaultValue
<Select
  isSearchable
  isClearable
  placeholder="GAMES"
  options={optionsAB}
  defaultValue={{
    value: apiData[0]?.games , 
    label: (optionsAB || []).filter(x => (x.value.includes(apiData[0]?.games)))[0]?.label
  }}
  onChange={(newValue, name) => handleChange(newValue, 'games')}
/>

你也可以在Java中正常使用它。


我认为这是使用自定义包吗? - Ahmed Elsayed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接