简体   繁体   中英

Reactjs redux-form fields - custom checkbox/radiobox component - bug in initial checked

I am working on a custom radiobutton/checkbox component -- based off the renderField. The component appears to render fine, but when I've added a "checked" parameter to this it breaks. The field is selected correctly - but when toggling options it looks like it tries to force check the old item.

//renderField

在此处输入图片说明

import React from 'react'

const renderField = ({input, label, type, meta: {touched, error, warning}}) => (
  <div className='field'>
    <label>
      {touched &&
        <span>
          {label}
        </span>
      }
      {touched &&
        ((
          error &&
            <span className="error">
              : {error}
            </span>) ||
          (
          warning &&
            <span className="warning">
              : {warning}
            </span>
        ))}
    </label>
    <div>
      <input {...input} placeholder={label} type={type} />
    </div>
  </div>
)

export default renderField

here is the new field -- the markup is different to the standard input fields.

//renderRadioCheckField

在此处输入图片说明

import React from 'react'
import _ from 'underscore';

function renderRadioCheckField({input, label, type, checked, meta: {touched, error, warning}}) {
  const randId = _.uniqueId('radiocheck_');

  return (
    <div className='field'>
      <div>
        <input {...input} placeholder={label} type={type} id={randId} checked={checked} />
        <label className="group-label" htmlFor={randId}>
          {label}
        </label>
      </div>
    </div>
  );
}


export default renderRadioCheckField

--

on my form component I am importing these in and calling them as such

  <Field name="test" type="text" component={renderField}  label="test" />

  <br/><br/>  
  <Field name="radio-group1" type="radio" component={renderRadioCheckField} value="check1" label="Apple2" />
  <Field name="radio-group1" type="radio" component={renderRadioCheckField} value="check2" label="Peach2" checked="true" />
  <Field name="radio-group1" type="radio" component={renderRadioCheckField} value="check3" label="Orange2" />

  <br/><br/>  
  <Field name="check-group1" type="checkbox" component={renderRadioCheckField} value="check1" label="Yes" />
  <Field name="check-group1" type="checkbox" component={renderRadioCheckField} value="check2" label="No" checked="true" />

Don't use the checked="true" . Instead do following in your componentDidMount() method of React Redux Form component.

componentDidMount(){
        const {radio-group1} = this.props;

        //Sets initial default checked value
        this.props.change('radio-group1','check2'); 
}

You can do same for checkboxes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM