How do I use Redux-form to get values from checkboxes?

旧巷老猫 提交于 2020-01-04 05:56:07

问题


How do you change the default boolean value for a checkbox in redux form to be the value you specify on the input itself?

For example, I have an input like this:

<input type="checkbox" value="Pages missing or out of order" {...issue1} />

When Redux form picks this up, it just gives me a true/false, even though I want the value "Pages missing or out of order"

Can I do something like this to get where I need to go so that when the form submits, it will submit the value "Pages missing or out of order, instead of true/false?

<input type="checkbox" onChange={value => console.log(value.target.value)} value="Pages missing or out of order" />

when I remove the {...issue1}, my custom onChange event handler will be called, but when I keep {...issue1}, it's completely ignored.

Thoughts?


回答1:


No, redux-form treats checkboxes as boolean values. You'll have to map the boolean to the string elsewhere.




回答2:


You need to use both the format property to map from string to boolean and the normalize property to map from boolean to string.

For Example,

If you have data saved in redux state that needs to be the strings '1' or '0', you need to use a <Field /> like below to map to the true and false default values of the redux-form checkbox

<Field
  name='myCheckbox'
  type='checkbox
  format={v => v === '1'} // converts redux state string to boolean
  normalize={v => v ? '1' : '0'} // converts checkbox boolean to string
/>

Using both format and normalize you keep your checkbox true and false mapped to '1' and '0' in your redux store.



来源:https://stackoverflow.com/questions/37954863/how-do-i-use-redux-form-to-get-values-from-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!