3

i have a react-select component which i made compatible with redux-form. My SelectInput component is this:

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

and i render it in my component which is a form

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

I've also set initial values to the container so as the state for this component has an initial value and it's working. My problem is that when i render the component the initial value does not show in the selection box and it's empty. Why is this happenning?

4

2 回答 2

4

你的形状是options什么?- 通常它是一个具有值和标签属性的对象数组:

[
  { label: "I like", value: "icecream" },
  { label: "Any", value: "Any" }
]

value您可以通过将 react-select的初始属性设置为选项数组中的值之一来设置它。或者,您也可以将其设置为不存在的选项,方法是给它一个带有标签和值的对象。这label是显示为value选择的内容。确实有点令人困惑,尽管它有点道理。

TL;博士

value={{ value: 0, label: 'Any' }}- 会成功的!

您也可以将初始值设置为您的选项值,它将显示出来。这意味着如果您有{ value: "Any", label: "Any" }选项value={'Any'},将在选择中显示“任何”。

希望这对你有用!

于 2017-04-07T12:40:19.600 回答
2

遇到了类似的问题。即使正确传递,输入值字段也始终未设置。在这种情况下,您可以创建一个input具有 value 属性(以及所有其他必需属性)的对象,也可以使用单独的属性selectedValue

 <Field
  id="side"
  name="side"
  component={SelectInput}
  options={sideOptions}
  value="Any"
  clearable={false}
  selectedValue={this.props.myvalue}
 />

const MySelect = props => (
  <Select
   {...props}
   value={(props.input.value) ? props.input.value : props.selectedValue}
   onChange={value => props.input.onChange(value)}
   onBlur={() => props.input.onBlur(props.input.value)}
   options={props.options}
   placeholder={props.placeholder}
  />
);
于 2017-05-10T04:01:44.307 回答