【问题标题】:Set select default value doesn't work设置选择默认值不起作用
【发布时间】:2018-03-13 23:01:25
【问题描述】:

使用 Bulma CSS 获得一点帮助,我制作了自定义组件,让我使用 redux-form 处理不同类型的输入。

我想为选择输入设置一个默认值。

import React from 'react';
import { Field } from 'redux-form';

const DropDownItem = ({ spec }) => {
  const { name, defaultValue, items, iconLeft } = spec;

  return (
    <div className="field">
      <div className="control has-icons-left">
        <div className="select is-fullwidth">
          <Field name={name} value={defaultValue} component="select">
            {/* loop for countries */}
            {items.map((country, i) => (
              <option value={country} key={i}>
                {country}
              </option>
            ))}
          </Field>
        </div>
        <div className="icon is-left">
          <i className={iconLeft} />
        </div>
      </div>
    </div>
  );
};

export default DropDownItem;

我在defaultValue 中有正确的值,但下拉菜单默认不选择此值。

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

    &lt;Field /&gt;value 由 redux-form 存储中的值控制。初始化时,您应该在配置中为您的 redux-form 表单设置 initialValues

    import React from 'react'
    import { Field, reduxForm } from 'redux-form'
    
    let MyFormComponent = props => {
        const { handleSubmit } = props;
        return (
            <form onSubmit={handleSubmit}>
                <Field name="fieldName" component="input" /> // this field's default value will be 'defaultValue', as set in initialValues
                ...
            </form>
        )
    }
    
    MyFormComponent = reduxForm({
        form: 'myForm',
        initialValues: {
            'fieldName': 'defaultValue',
            ...
        }
    })(MyFormComponent)
    
    export default MyFormComponent;
    

    您也可以将initialValues 作为prop 传递给您的表单组件。

    source

    【讨论】:

    • 好的,如果我想用第二种解决方案来玩生命周期,我必须将我的无状态组件更改为一个类。对于第一个 fieldName 是我在这里设置的名称,对吧? &lt;Field name={name}... &gt;
    • 是的,我在initialValues 中输入的'fieldName' 就是您在name={name} 中设置的。同样你是对的,要使用生命周期组件,你需要将此无状态组件转换为一个类:class MyFormComponent extends React.Component { ... }
    【解决方案2】:

    根据this thread on Github,似乎defaultValue 已在redux-form 中被禁用

    相反,您可以使用redux-forminitialValues API

    你可以阅读更多关于initialValueson Redux Form Docsinitializefromstate的信息

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 2020-10-03
      相关资源
      最近更新 更多