如何在 react-select 中设置默认值

How to set a default value in react-select

提问人:RamAlx 提问时间:4/19/2017 最后编辑:Penny LiuRamAlx 更新时间:11/1/2023 访问量:576598

问:

我在使用 react-select 时遇到了问题。我使用 redux 表单,并使我的 react-select 组件与 redux 表单兼容。代码如下:

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>

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

reactjs 默认值 react-select

评论

0赞 Ved 4/19/2017
这是正确的:value={props.input.value}。您面临的问题是什么?
2赞 RamAlx 4/19/2017
我的问题是我希望我的选择在我第一次渲染它时有一个 defaultValue,但我不能
1赞 Ved 4/19/2017
props.input.value 首先呈现时的值是多少?
0赞 RamAlx 4/19/2017
那是我的问题。如何设置默认值?
0赞 Ved 4/19/2017
你想要什么价值?

答:

148赞 Ved 4/19/2017 #1

我想你需要这样的东西:

const MySelect = props => (
<Select
    {...props}
    value = {
       props.options.filter(option => 
          option.label === 'Some label')
    }
    onChange = {value => props.input.onChange(value)}
    onBlur={() => props.input.onBlur(props.input.value)}
    options={props.options}
    placeholder={props.placeholder}
  />
);

#EDIT 1 : 新版本

const MySelect = props => (
<Select
    {...props}
     options={props.options} 
    onChange = {value => props.input.onChange(value)}
    onBlur={() => props.input.onBlur(props.input.value)}//If needed
    defaultValue={props.defaultValue || 'Select'}
    options={props.options}
    placeholder={props.placeholder}
  />
);

评论

8赞 Joseph Juhnke 8/4/2017
与 redux/react 绑定的要点是让 ui 实时反映对象的值。这种方法解耦了这种绑定。考虑在 reducer 中设置默认值。
3赞 Ved 8/4/2017
@JosephJuhnke先检查问题。这是设置默认值的方法。
8赞 Sang 10/14/2018
selectedValue已更改为 。react-select.com/props 检查文档value
32赞 Hongbo Miao 1/31/2019
新版本中现在有字段。defaultValue
8赞 andyCao 8/1/2019
棘手的是,您需要将所选对象设置为“defaultValue”字段,而不是选项的值。例如 0,1,2
14赞 Drizzel 7/7/2017 #2

我遇到了类似的错误。确保您的选项具有 value 属性。

<option key={index} value={item}> {item} </option>

然后,将最初选择元素值与选项值匹配。

<select 
    value={this.value} />

评论

0赞 user2026178 8/15/2017
我认为这是最好/最优雅的解决方案。我这样想对吗?
0赞 raghul 8/2/2018
如果这样做,值不会改变,你有写 onChange 函数太设置更改
5赞 Mike Goatly 1/16/2020
这是针对普通的 HTML <select> 元素,而不是 react-select <Select>,这是问题的用途。套管可以使一切变得不同:)
2赞 Joseph Juhnke 8/4/2017 #3

我自己刚刚经历了这个,并选择在 reducer INIT 函数中设置默认值。

如果你用 redux 绑定了你的选择,那么最好不要用一个不代表实际值的 select 默认值来“解绑”它,而是在初始化对象时设置这个值。

0赞 naamadheya 10/20/2017 #4

如果你的选择是这样的

var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two' }
];

您应该匹配{props.input.value}'value'{props.options}

意思是,应该是 either 或props.input.value'one''two'

1赞 Isaac Pak 7/15/2018 #5

如果你没有使用 redux-form,而是使用本地状态进行更改,那么你的 react-select 组件可能如下所示:

class MySelect extends Component {

constructor() {
    super()
}

state = {
     selectedValue: 'default' // your default value goes here
}

render() {
  <Select
       ...
       value={this.state.selectedValue}
       ...
  />
)}
121赞 TejasPancholi 8/3/2018 #6

我使用了 defaultValue 参数,下面是我如何实现默认值以及在从下拉列表中选择选项时更新默认值的代码。

<Select
  name="form-dept-select"
  options={depts}
  defaultValue={{ label: "Select Dept", value: 0 }}
  onChange={e => {
              this.setState({
              department: e.label,
              deptId: e.value
              });
           }}
/>

评论

27赞 Dennis Liu 2/18/2019
谢谢,现在我知道 defaultValue 接受对象而不仅仅是值。
2赞 Alex 4/15/2019
不是根据 React 文档或智能感知,它没有: reactjs.org/docs/uncontrolled-components.html#default-values
6赞 Rashad Nasir 1/8/2021
@Alex - (对于 2 年后在座的任何人),这个问题指的是组件库 react-select。您链接到的文档引用了本机 HTML select 元素。
0赞 Miftah Classifieds 4/7/2023
defaultValue as 值中的诀窍不是简单的 val,而是取对象。谢谢
54赞 eedrah 9/7/2018 #7

如果你来这里是为了 react-select v2,但仍然有问题 - 版本 2 现在只接受一个对象作为 , 等。valuedefaultValue

也就是说,尝试使用 ,而不仅仅是 。value={{value: 'one', label: 'One'}}value={'one'}

评论

3赞 Toskan 7/19/2020
不完全的。如果将 value 设置为该值,则无法再更改 valuie
0赞 eedrah 7/20/2020
@Toskan - 是的,这是 ReactJS 和单向数据绑定的原则之一,并且影响所有表单元素,而不仅仅是这个库。如果你选择有一个受控组件,你需要在 react 之外自己处理更改。这个答案谈到了它,并链接到 React 文档:stackoverflow.com/questions/42522515/......
0赞 Toskan 7/20/2020
好吧,很公平,那么你解决了什么问题?也就是说,对值进行硬编码?
0赞 eedrah 7/21/2020
这里给出的案例只是一个例子。在您的应用程序中,这将是一个具有相同结构的变量/道具。{value: 'one', label: 'One'}
0赞 Amartya Mishra 6/11/2021
一种方式的数据绑定并不意味着一旦从 prop 设置了数据,就不能在子组件中更改(如果愿意的话)。这正是如果使用而不是defaultValuevalue
12赞 Dan Meigs 11/15/2018 #8

扩展 @isaac-pak 的答案,如果您想在 prop 中将默认值传递给您的组件,您可以在 componentDidMount() 生命周期方法中将其保存为状态,以确保第一次选择默认值。

请注意,我更新了以下代码以使其更加完整,并使用空字符串作为每个注释的初始值。

export default class MySelect extends Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedValue: '',
        };
        this.handleChange = this.handleChange.bind(this);

        this.options = [
            {value: 'foo', label: 'Foo'},
            {value: 'bar', label: 'Bar'},
            {value: 'baz', label: 'Baz'}
        ];

    }

    componentDidMount() {
        this.setState({
            selectedValue: this.props.defaultValue,
        })
    }

    handleChange(selectedOption) {
        this.setState({selectedValue: selectedOption.target.value});
    }

    render() {
        return (
            <Select
                value={this.options.filter(({value}) => value === this.state.selectedValue)}
                onChange={this.handleChange}
                options={this.options}
            />
        )
    }
}

MySelect.propTypes = {
    defaultValue: PropTypes.string.isRequired
};

评论

0赞 Jason Rice 2/22/2019
我明白了:警告:prop on 不应该为空。请考虑使用空字符串来清除组件或不受控制的组件。valueselectundefined
0赞 alexventuraio 7/1/2019
我正在做同样的事情,我收到以下警告:Warning: A component is changing a controlled input of type hidden to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa).
0赞 Dan Meigs 7/2/2019
@AlexVentura 我已经使我的代码更完整一些,并在我的系统上进行了测试。我没有收到有关受控输入的警告。尝试根据我编辑的回复更新您的代码,并发回您找到的内容。
0赞 Parveen Chauhan 6/17/2019 #9

自动选择 in select 的值。

enter image description here

<div className="form-group">
    <label htmlFor="contactmethod">Contact Method</label>
    <select id="contactmethod" className="form-control"  value={this.state.contactmethod || ''} onChange={this.handleChange} name="contactmethod">
    <option value='Email'>URL</option>
    <option value='Phone'>Phone</option>
    <option value="SMS">SMS</option>
    </select>
</div>

在 select 标记中使用 value 属性

value={this.state.contactmethod || ''}

解决方案对我有用。

0赞 Coded Container 2/2/2020 #10
  1. 在构造函数中为默认选项文本创建状态属性
    • 不要担心默认选项值
  2. 向 render 函数添加选项标记。仅使用状态和三元表达式显示
  3. 创建一个函数以在选择选项时进行处理
  4. 将此事件处理程序函数中默认选项值的状态更改为 null

    Class MySelect extends React.Component
    {
        constructor()
        {
            super()
            this.handleChange = this.handleChange.bind(this);
            this.state = {
                selectDefault: "Select An Option"
            }
        }
        handleChange(event)
        {
            const selectedValue = event.target.value;
            //do something with selectedValue
            this.setState({
                selectDefault: null
            });
        }
        render()
        {
            return (
            <select name="selectInput" id="selectInput" onChange={this.handleChange} value= 
                {this.selectedValue}>
             {this.state.selectDefault ? <option>{this.state.selectDefault}</option> : ''}
                {'map list or static list of options here'}
            </select>
            )
        }
    }
    
1赞 Sergio Hidalgo Robles 5/15/2020 #11

我经常使用这样的东西。

此示例中 props 的默认值

if(Defaultvalue ===item.value) {
    return <option key={item.key} defaultValue value={item.value}>{plantel.value} </option>   
} else {
    return <option key={item.key} value={item.value}>{plantel.value} </option> 
}
8赞 Dasun Bandara 6/4/2020 #12

像这样使用 defaultInputValue 属性:

<Select
   name="name"
   isClearable
   onChange={handleChanges}
   options={colourOptions}
   isSearchable="true"
   placeholder="Brand Name"
   defaultInputValue="defaultInputValue"
/>

          

更多参考 https://www.npmjs.com/package/react-select

2赞 Ivan Seredkin 11/2/2020 #13

如果在选项中使用组,则需要进行深度搜索:

options={[
  { value: 'all', label: 'All' },
  {
    label: 'Specific',
    options: [
      { value: 'one', label: 'One' },
      { value: 'two', label: 'Two' },
      { value: 'three', label: 'Three' },
    ],
  },
]}
const deepSearch = (options, value, tempObj = {}) => {
  if (options && value != null) {
    options.find((node) => {
      if (node.value === value) {
        tempObj.found = node;
        return node;
      }
      return deepSearch(node.options, value, tempObj);
    });
    if (tempObj.found) {
      return tempObj.found;
    }
  }
  return undefined;
};
4赞 Mitesh K 4/16/2021 #14

pass 对象:value

<Select
                    isClearable={false}
                    options={[
                      {
                        label: 'Financials - Google',
                        options: [
                          { value: 'revenue1', label: 'Revenue' },
                          { value: 'sales1', label: 'Sales' },
                          { value: 'return1', label: 'Return' },
                        ],
                      },
                      {
                        label: 'Financials - Apple',
                        options: [
                          { value: 'revenue2', label: 'Revenue' },
                          { value: 'sales2', label: 'Sales' },
                          { value: 'return2', label: 'Return' },
                        ],
                      },
                      {
                        label: 'Financials - Microsoft',
                        options: [
                          { value: 'revenue3', label: 'Revenue' },
                          { value: 'sales3', label: 'Sales' },
                          { value: 'return3', label: 'Return' },
                        ],
                      },
                    ]}
                    className="react-select w-50"
                    classNamePrefix="select"
                    value={{ value: 'revenue1', label: 'Revenue' }}
                    isSearchable={false}
                    placeholder="Select A Matric"
                    onChange={onDropdownChange}
                  />

评论

2赞 Arca Ege Cengiz 4/16/2021
对于任何未来的读者来说,这可能是最好和最简单的选择。value prop 也可以在没有 redux 的情况下工作。
-3赞 Rajdip 5/4/2021 #15

您可以简单地执行此操作:

在 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 中,for .使用如下示例: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 普通版中使用它。

评论

0赞 Ahmed Elsayed 9/20/2022
我认为它是否使用自定义包?
1赞 IronmanX46 6/21/2021 #16

用。确保 中的值在选择字段中给出的选项中。<select value={stateValue}>stateValue

-2赞 Behram Bazo 6/24/2021 #17

在 react-select 中,如果要定义自定义标签,请尝试这样做。

  <Select
    getOptionLabel={({ name }) => name}
  />
1赞 bFunc 8/6/2021 #18

几点:

  1. defaultValue 适用于初始渲染,它不会在顺序渲染传递时更新。确保在手头有 defaultValue 后呈现 Select。

  2. defaultValue 应该以 Object 或 Array of Objects 的形式定义,如下所示: ,最无懈可击的方法是将其设置为选项列表项:{value:'1', label:'Guest'}myOptionsList[selectedIndex]

5赞 Shamsul Arefin 10/29/2021 #19

当我按照上面的所有答案进行操作时,我想到了,我应该写这个。

您必须设置 prop ,而不是 DefaultValue。 我花了几个小时使用它,阅读了文档,他们提到使用 DefaultValue,但它不起作用。 正确的方式是,

options=[{label:'mylabel1',value:1},{label:'mylabel2',value:2}]
seleted_option={label:'mylabel1',value:1}

<Select
options={options}
value={selected_option}/>

评论

0赞 ronate 8/2/2022
在这种情况下,您还可以将默认值设置为选项的索引<Select options={options} value={options[0]} />
2赞 Anas Abu Farraj 4/6/2022 #20

使用代替defaultValueselected

如果要从菜单中隐藏该值,请使用:hidden

<option defaultValue hidden>
   {'--'}
</option>
{options.map(opt => (
    <option key={opt} value={opt.replaceAll(/[,'!?\s]/gi, '')}>
       {opt}
    </option>
))}
0赞 Jack Collins 4/20/2022 #21

想用 Hooks 给我加两分钱,

您可以在下拉菜单中订阅道具

import React, { useEffect, useState } from 'react';
import Select from 'react-select';

const DropDown = (props) => {
  const { options, isMulti, handleChange , defaultValue } = props;
  const [ defaultValueFromProps, setdefaultValueFromProps ] = useState(undefined)

  useEffect(() => {
    
    if (defaultValue) {
      setdefaultValueFromProps(defaultValue)
    }
  }, [props])
  
  const maybeRenderDefaultValue = () => {
    if (defaultValue) {
      return { label: defaultValueFromProps, value: defaultValueFromProps }
    } 
  }
  return (
    <div>
      <Select 
        width='200px'
        menuColor='red'
        isMulti={isMulti} 
        options={options} 
        value={maybeRenderDefaultValue()}
        clearIndicator
        onChange={(e) => handleChange(e)}
      />
    </div>
  )
}

export default DropDown;

然后在父组件中传递初始值或从状态更改的值

<DropDown options={GenreOptions} required={true} defaultValue={recipeGenre === undefined ? recipe.genre : recipeGenre} handleChange={handleGenreChange}/>

然后,如果它是一个新表单(没有默认值),您不必担心,因为 useEffect 将忽略任何设置

-1赞 KingJoeffrey 4/25/2022 #22

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。

我需要用defaultValue({title:“this”, _id: “that”}) 设置我的

-1赞 Paul 6/15/2022 #23
<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赞 Muhammad Usman 8/23/2022 #24

React-hook-form 的钩子中提供参数useFormdefaultValues

const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      select: { label: "20", value: 20 },
    },
  });

react-select 组件

<Select
     optons={[
        { value: "20", label: "20" },
        { value: "30", label: "30" },
        { value: "25", label: "25" },
      ]}
/>

为组件提供属性defaultValuereact-select

<Select
   defaultValue={{ label: "20", value: 20 }
   optons={[
      { value: "20", label: "20" },
      { value: "30", label: "30" },
      { value: "25", label: "25" },
   ]}
/>
-1赞 Ahmed Elsayed 9/20/2022 #25

我认为您可以在标签上使用选定的道具

         <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}

0赞 dharmveer bangar 10/19/2023 #26
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赞 URVESH RADADIYA 11/1/2023 #27
    <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>