【问题标题】:How to use a select input type with redux-form?如何在 redux-form 中使用选择输入类型?
【发布时间】:2017-03-12 22:22:00
【问题描述】:

我搜索并尝试了很多使用 redux-form 库在我的反应表单中使用选择输入类型。

一切正常,所有其他输入类型都可以,但以下操作的选择不是:初始化、检索提交的值等。

我尝试使用带有“选择”的模型道具和我自己的函数来渲染它。当我为模型使用选择版本时,我设法获取组合框字段的选项,但我无法设置值并在提交时检索它。使用我自己的功能,我什至无法将选项设置为列表...

这是我的代码:

// FormComponent file
const { handleSubmit } = this.props;
...
<form onSubmit={handleSubmit(this.props.onSubmitProfileUpdate)}>
    <Field name='ranking' className='input-row form-group form-control' component={renderSelectField}>
                        {tennisRankings.map(ranking =>
                          <option value={ranking} key={ranking}>{ranking}</option>
                        )}
                      </Field>
...
ProfileForm.propTypes = {
  user: React.PropTypes.object,
  fields: React.PropTypes.shape({
    firstname: React.PropTypes.string,
    lastname: React.PropTypes.string,
    ranking: React.PropTypes.string,
    email: React.PropTypes.string,
    telephone: React.PropTypes.string,
    city: React.PropTypes.string
  }),
  errorMessage: React.PropTypes.string,
  confirmationMessage: React.PropTypes.string,
  onSubmitProfileUpdate: React.PropTypes.func.isRequired,
  handleSubmit: propTypes.handleSubmit,
  initialize: propTypes.initialize
};

export default reduxForm({
  form: 'profile',
  validate: validateProfileForm
})(ProfileForm);

渲染字段的函数:

// Functions shared
export const renderSelectField = (field) => {
  var styles = {};
  var containerStyle = getInputStylesContainer();

      if (field.input.value || field.meta.touched) {
        if (!field.meta.error) {
          styles = getInputStylesSuccess();
          containerStyle = classNames(containerStyle, {'has-success': true});
        } else {
          styles = getInputStylesError();
          containerStyle = classNames(containerStyle, {'has-error': true});
        }
      }

      return (<div className={containerStyle}>
        {displayInputLabel(styles.idInput, field.label)}
        <select {...field.input} className='form-control' id={styles.idInput} value={field.input.value} type={field.type} placeholder={field.label} aria-describedby={styles.ariaDescribedBy} />
        <span className={styles.glyphicon} aria-hidden='true' />
        {field.meta.touched && field.meta.error &&
        displayErrorMessage(field.meta.error)}
      </div>);
    };

你有任何线索来执行这个简单的动作吗?放纵一下,我是初学者:)

非常感谢您的帮助:)

编辑:

这是我初始化表单值的方式:

// FormComponent file
handleInitialize () {
    // TODO: Manage properly user not available case (redux form reason ?)
    if (this.props.user.firstname === undefined) return;
    const initData = {
      'firstname': this.props.user.firstname.toString(),
      'lastname': this.props.user.lastname.toString(),
      'city': this.props.user.city === undefined ? '' : this.props.user.city.toString(),
      'email': this.props.user.email.toString(),
      'ranking': this.props.user.ranking.toString(),
      'telephone': this.props.user.telephone === undefined ? '' : this.props.user.telephone.toString()
    };
    console.log('Ranking', this.props.user.ranking);
    this.props.initialize(initData);
  }

  componentDidMount () {
    this.handleInitialize();
  }

....

export default reduxForm({
  form: 'profile',
  validate: validateProfileForm
})(ProfileForm);

【问题讨论】:

    标签: javascript reactjs redux-form


    【解决方案1】:

    这是来自official docs 的简单选择字段的示例:

    <div>
      <label>Favorite Color</label>
      <div>
        <Field name="favoriteColor" component="select">
          <option></option>
          <option value="ff0000">Red</option>
          <option value="00ff00">Green</option>
          <option value="0000ff">Blue</option>
        </Field>
      </div>
    </div>
    

    您的实现没有映射options,因此select 不起作用。

    旁注 要传递初始值,您应该在 reduxForm 配置中添加 initialValues 属性,而不是在字段中添加 value 属性。下面的例子:

    export default reduxForm({
      form: 'profile',
      validate: validateProfileForm,
      initialValues: { ... }
    })(ProfileForm);
    

    【讨论】:

    • 感谢您的回答,我会试试看!目前我正在使用 redux-form 中的 initiliize 函数来初始化我的值(请参阅我编辑的问题)。你知道你的解决方案和初始化函数之间的区别吗?你会建议我使用什么?
    • @ClementLevesque 我不确定你的初始化函数在哪里。它在文档中不存在(redux-form.com/6.5.0/docs/api/ReduxForm.md),initialValues是官方文档规定的方法,所以我会坚持下去。
    • @ClementLevesque 我检查了您的编辑 - 您绝对应该使用 initialValues,因为 redux-form 将完成所有工作(需要维护的代码更少)。
    • 感谢您的帮助,我将尝试使用 initialValues。有关信息,我发现该功能是文档:redux-form.com/6.0.5/docs/api/Props.md
    • 我无法完全理解您所说的“没有映射 options”,所以我决定添加空白选项 (&lt;option&gt;&lt;/option&gt;),这会导致用户更改选择,因此值被捕获。否则,如果用户不更改值,它似乎不会被我的代码捕获。把它写在这里以防它帮助别人。
    【解决方案2】:

    选择评分示例:redux-form

    如何在 redux-form 中处理选择

    import React, { Component } from 'react';
    import { Link } from 'react-router-dom';
    /*------- connect react with redux --------*/
    import { connect } from 'react-redux';
    /*------- action which all data to data base --------*/
    import { addProduct } from '../actions'
    /*------- redux form --------*/
    import { Field, reduxForm } from 'redux-form';
    
    class Form extends Component {
    
        //PRISTINE / DIRTY // TOUCHED / ERROR : events in redux-form 
    
      
    
        /*------- renderSelectField  --------*/
    
      
        renderSelectField(field){
            const className = `form-input ${field.meta.touched && field.meta.error ? 'has-error':''}`;
            return(
                <div className={className}>
                    <label>{field.myLabel}</label>
    
                    
                   <select  {...field.input}  >
                        {field.children}
                   </select>
    
                     <div className="error">
                        {field.meta.touched ? field.meta.error:''}
                    </div>
                </div>
            )
        }
    /*------- onSubmit() : runs on submit  --------*/
        onSubmit(values){
    
           // const error = this.validate(values);
           // console.log(error)
            console.log(values)
            this.props.dispatch(addProduct({
                values
             }))
        }
    
    
        render(){
            return(
                <div className="Form">
                    <div className="top">
                        <h3>Add a Message</h3>
                        <Link to="/">Back</Link>
                    </div>
                    <form onSubmit={this.props.handleSubmit((event)=>this.onSubmit(event))}>
    
                        <Field
                            myLabel="Select Rating"                    
                            name="rating"
                            component={this.renderSelectField}>
                            <option></option>
                            <option value='1'>1</option>
                            <option value='2'>2</option>
                            <option value='3'>3</option>
                            <option value='4'>4</option>
                            <option value='5'>5</option>
                        </Field>
     
    
                        <button type="submit">Submit</button>
    
                    </form>
                </div>
            )
        }
    }
    /*------- validate() : validates our form  --------*/
    
    
    function validate(values){
        const errors = {};
    
       
    
        if(!values.rating){
            errors.rating = "The rating is empty"
        }
    
    
        return errors;
    }
        /*------- it returns messages when action is called and state going to change  --------*/
    
    function mapStateToProps(state){
    
        return {
            product: state.data
        }
    }
    
        /*------- reduxForm : connects redux-form with react form   --------*/
    
    export default reduxForm({
        validate,
        form:'AddProduct',
    })(
        connect(mapStateToProps,{addProduct})(Form)
    )

    【讨论】:

      猜你喜欢
      • 2018-08-13
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      相关资源
      最近更新 更多