简体   繁体   English

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

[英]How to set a default value in react-select

I have an issue using react-select.我在使用 react-select 时遇到问题。 I use redux form and I've made my react-select component compatible with redux form.我使用 redux 表单,并且我的 react-select 组件与 redux 表单兼容。 Here is the code:这是代码:

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}
    />
);

and here how I render it:以及我如何渲染它:

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

But the problem is that that my dropdown has not a default value as I wish.但问题是我的下拉列表没有我希望的默认值。 What I'm doing wrong?我做错了什么? Any ideas?有任何想法吗?

I guess you need something like this:我想你需要这样的东西:

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}
  />
);

I used the defaultValue parameter, below is the code how I achieved a default value as well as update the default value when an option is selected from the drop-down.我使用了 defaultValue 参数,下面是我如何获得默认值以及从下拉列表中选择一个选项时更新默认值的代码。

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

If you've come here for react-select v2, and still having trouble - version 2 now only accepts an object as value , defaultValue , etc.如果您来这里是为了 react-select v2,但仍然遇到问题 - 版本 2 现在只接受一个对象作为valuedefaultValue等。

That is, try using value={{value: 'one', label: 'One'}} , instead of just value={'one'} .也就是说,尝试使用value={{value: 'one', label: 'One'}} ,而不仅仅是value={'one'}

I was having a similar error.我遇到了类似的错误。 Make sure your options have a value attribute.确保您的选项具有 value 属性。

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

Then match the selects element value initially to the options value.然后将选择元素值最初与选项值匹配。

<select 
    value={this.value} />

Extending on @isaac-pak's answer, if you want to pass the default value to your component in a prop, you can save it in state in the componentDidMount() lifecycle method to ensure the default is selected the first time.扩展@isaac-pak 的答案,如果您想将默认值传递给 prop 中的组件,您可以将其保存在 componentDidMount() 生命周期方法中的 state 中,以确保第一次选择默认值。

Note, I've updated the following code to make it more complete and to use an empty string as the initial value per the comment.请注意,我已更新以下代码以使其更完整,并使用空字符串作为每个注释的初始值。

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

Use defaultInputValue props like so:像这样使用 defaultInputValue 道具:

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

          

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

I just went through this myself and chose to set the default value at the reducer INIT function.我自己刚刚经历了这个并选择在 reducer INIT 函数中设置默认值。

If you bind your select with redux then best not 'de-bind' it with a select default value that doesn't represent the actual value, instead set the value when you initialize the object.如果您使用 redux 绑定您的选择,那么最好不要使用不代表实际值的选择默认值“解除绑定”,而是在初始化对象时设置该值。

You need to do deep search if you use groups in options:如果在选项中使用组,则需要进行深度搜索:

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

If you are not using redux-form and you are using local state for changes then your react-select component might look like this:如果您没有使用 redux-form 并且您使用本地状态进行更改,那么您的 react-select 组件可能如下所示:

class MySelect extends Component {

constructor() {
    super()
}

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

render() {
  <Select
       ...
       value={this.state.selectedValue}
       ...
  />
)}

I'm using frequently something like this.我经常使用这样的东西。

Default value from props in this example本例中 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> 
}

pass value object :传递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}
                  />

Use <select value={stateValue}> .使用<select value={stateValue}> Make sure that the value in stateValue is among the options given in the select field.确保stateValue中的值在选择字段中给出的选项中。

If your options are like this如果你的选择是这样的

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

Your {props.input.value} should match one of the 'value' in your {props.options}{props.input.value}应匹配的一个'value'在您的{props.options}

Meaning, props.input.value should be either 'one' or 'two'意思是, props.input.value应该是'one''two'

To auto-select the value of in select.自动选择 in select 的值。

在此处输入图片说明

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

Use the value attribute in the select tag在 select 标签中使用 value 属性

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

the solution is working for me.解决方案对我有用。

  1. Create a state property for the default option text in the constructor在构造函数中为默认选项文本创建状态属性
    • Don't worry about the default option value不用担心默认选项值
  2. Add an option tag to the render function.向渲染函数添加选项标签。 Only show using state and ternary expression仅显示使用状态和三元表达式
  3. Create a function to handle when an option was selected创建一个函数以在选择选项时进行处理
  4. Change the state of the default option value in this event handler function to 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> ) } }

In react-select if you want to define for the custom label, try this.在 react-select 中,如果你想定义自定义标签,试试这个。

  <Select
    getOptionLabel={({ name }) => name}
  />

couple of points:几点:

  1. defaultValue works for initial render, it will not be updated on sequential render passes. defaultValue适用于初始渲染,它不会在顺序渲染过程中更新。 Make sure you are rendering your Select after you have defaultValue in hand.确保在手头有defaultValue之后呈现您的 Select 。

  2. defaultValue should be defined in form of Object or Array of Objects like this: {value:'1', label:'Guest'} , most bulletproof way is to set it as item of options list: myOptionsList[selectedIndex] defaultValue应以对象或对象数组的形式定义,如下所示: {value:'1', label:'Guest'} ,最安全的方法是将其设置为选项列表的项目: myOptionsList[selectedIndex]

As I followed all the answers above, it came to my mind, I should write this.当我按照上面的所有答案进行操作时,我想到了,我应该写这个。

you have to set the prop value , not the DefaultValue .你必须设置 prop,而不是DefaultValue I spent hours by using this, read the documentation, they mentioned to use the DefaultValue, but it is not working.我花了几个小时来使用它,阅读文档,他们提到使用 DefaultValue,但它不起作用。 correct way would be,正确的方法是,

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

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

Use defaultValue instead of selected使用defaultValue而不是selected

If you want to hide the value from the menu, use hidden :如果要从菜单中隐藏值,请使用hidden

<option defaultValue hidden>
   {'--'}
</option>
{options.map(opt => (
    <option key={opt} value={opt.replaceAll(/[,'!?\s]/gi, '')}>
       {opt}
    </option>
))}

Wanted to add my two cents to this, using Hooks,想用 Hooks 给我加两分钱,

You can subscribe to props in the DropDown你可以在 DropDown 中订阅 props

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;

and then in the parent component either pass the initial value or changed value from state然后在父组件中从 state 传递初始值或更改值

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

Then if it's a fresh form (no default value) you won't have to worry since the useEffect will ignore setting anything然后,如果它是一个新的形式(没有默认值),你不必担心,因为 useEffect 会忽略设置任何东西

In useForm hook of React-hook-form provide defaultValues parameterReact-hook-formuseForm hook 中提供defaultValues参数

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

react-select component反应选择组件

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

OR或者

provide defaultValue attribute to react-select componentreact-select组件提供defaultValue属性

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

i think you can use selected prop at tag我认为您可以在标签处使用选定的道具

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

Look at this selected={plan.name == i.name} also take notice about value update defaultValue={plan.name}看看这个selected={plan.name == i.name}还要注意值更新defaultValue={plan.name}

2022 example with Redux react with useSelector 2022 示例与 Redux 与 useSelector 反应

As of 2022 there is a defaultValue option in react-select.截至 2022 年,react-select 中有一个 defaultValue 选项。 Please note that if you are using getOptionLabel, and getOptionValue, you need to make your default value match those option params you set....请注意,如果您使用 getOptionLabel 和 getOptionValue,您需要使您的默认值与您设置的那些选项参数相匹配......

for example例如


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"
              })}
            />


rather than setting your defaultValue with {label: "this", value: "that}而不是用 {label: "this", value: "that} 设置你的 defaultValue

I needed to set mine with defaultValue({title:"this", _id: "that"})我需要设置我的 defaultValue({title:"this", _id:"that"})

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

use selected will serve the purpose of default value text使用 selected 将达到默认值文本的目的

You can simply do this as:你可以简单地这样做:

In react-select, initial options value在 react-select 中,初始选项值

const optionsAB = [
  { value: '1', label: 'Football' },
  { value: '2', label: 'Cricket' },
  { value: '3', label: 'Tenis' }
];

API giving only: API 仅提供:

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

In react-select, for defaultValue=[{value: 1, label: Hi}] .在 react-select 中,对于defaultValue=[{value: 1, label: Hi}] Use defaultValue like this example:像这个例子一样使用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')}
/>

You can use this in Java normal also.您也可以在 Java 中正常使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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