react-select:在多选下拉菜单中预先选择一个值

时间:2018-10-23 18:28:10

标签: javascript reactjs react-select

我继承了我的第一个React应用,我需要做一个看起来非常简单的更改。

此更改位于电子邮件注册页面上,该页面上的用户具有多选下拉菜单,以表明他们有兴趣了解的内容。我的简单目标:使下拉菜单中的一项显示为预选状态。 (最终,我会传递一个值,因此有时只选择它)。在此示例中,列表值/标签来自DESSERT_TYPES,我想预选该列表中的值之一:“ Sheet cake”。

通读react-select docs / examples,看来我只需要提供一个价值支持,但我尝试在Field定义中添加value= 'Sheet cake'value={{label: "Sheet cake", value: "Sheet cake"}}等不同的变体,ReactSelectAdapter或类构造函数中(用冒号而不是=),似乎没有任何作用:菜单仍只显示未选择任何内容的占位符文本。我也尝试使用defaultOptions和loadOptions,但也没有运气。

下面给出的所有代码都在同一个EmailSignup.js文件中。

有问题的渲染位是:

<div className="email-modal-input-wrap">
  <label className="email-modal-label" htmlFor="interest-input">
    Please select your interest from the list below:
  </label>
  <Field
    name="interest"
    component={ ReactSelectAdapter }
    options={ DESSERT_TYPES }
    placeholder="I'm interested in a project about..."
    isMulti
    value= 'Sheet cakes'
    id="interest-input"
    />
  <label className="email-modal-hidden-label" htmlFor="interest-input">Interest</label>
</div>

通过以下方式定义ReactSelectAdapter组件:

const ReactSelectAdapter = ({ input, ...rest }) => (
  <Creatable
    { ...input }
    { ...rest }
    styles={DROPDOWN_STYLES}
    classNamePrefix="react-select"
    searchable
  />
)

EmailSignup类的构造函数具有:

class EmailSignup extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      submitted: false,
      success: 'hidden',
      error: 'hidden',
      existing: 'hidden',
      modalIsOpen: true,
      location: undefined
    }

其中包括:

import React from 'react'
import Modal from 'react-modal'
import { Form, Field } from 'react-final-form'
import axios from 'axios'
import ProjectLogoList from './ProjectLogoList'
import PropTypes from 'prop-types'
import { PROJECT_DATA } from '../Utils/data/ProjectData'
import { DESSERT_TYPES } from '../Utils/data/dessertTypes'
import Creatable from 'react-select/lib/Creatable'
import ReactGA from 'react-ga';

我在这里可能想念什么?

1 个答案:

答案 0 :(得分:1)

要设置初始值,请将一个对象传递到value道具:

<Creatable
    // ...other props
    options={DESSERT_TYPES}
    value={{label: "Cake", value: "cake"}}
/>
相关问题