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

How to set a default value in react-select

我在使用 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>

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

我猜你需要这样的东西:

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

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

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

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

<select 
    value={this.value} />

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

如果您将 select 与 redux 绑定,那么最好不要 'de-bind' 使用不代表实际值的 select 默认值,而是在初始化时设置该值物体。

如果你的选择是这样的

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

您的 {props.input.value} 应与 {props.options}

中的 'value' 之一匹配

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

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

class MySelect extends Component {

constructor() {
    super()
}

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

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

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

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

如果你来这里是为了 react-select v2,但仍然遇到问题 - 版本 2 现在只接受对象 valuedefaultValue

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

扩展@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
};

到auto-select的值在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>

使用 select 标签中的值属性

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

这个解决方案对我有用。

  1. 在构造函数中为默认选项文本创建一个状态属性
    • 不用担心默认选项值
  2. 为渲染函数添加一个选项标签。仅显示使用状态和三元表达式
  3. 创建一个函数以在选择选项时进行处理
  4. 将此事件处理函数中默认选项值的状态更改为空

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

我经常使用这样的东西。

Default value from props in this example

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

像这样使用 defaultInputValue 道具:

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

          

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

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

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

通过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}
                  />

您可以简单地这样做:

在 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' }
];

在反应中-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 中正常使用它。

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

在react-select如果你想为自定义标签定义,试试这个。

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

几点:

  1. defaultValue 适用于初始渲染,它不会在顺序渲染过程中更新。确保在手头有 defaultValue 之后渲染 Select。

  2. defaultValue 应该以对象或对象数组的形式定义,如下所示:{value:'1', label:'Guest'},最安全的方法是将其设置为项目选项列表:myOptionsList[selectedIndex]

按照上面所有的回答,我想到了,我应该写这个。

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

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

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

使用defaultValue代替selected

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

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

想用 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;

然后在父组件中传递初始值或从 state

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

那么如果它是一个新的形式(没有默认值)你就不用担心因为 useEffect 会忽略任何设置

2022 示例与 Redux 与 useSelector 反应

截至 2022 年,react-select 中有一个默认值选项。请注意,如果您使用 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"})