如何在反应最终形式中更改复选框的格式

时间:2021-06-08 18:01:23

标签: javascript reactjs react-final-form

我通过 react final form 实现了表单

const products=  [
    { label: "T Shirt", value: "tshirt" },
    { label: "White Mug", value: "cup" },
    { label: "G-Shock", value: "watch" },
    { label: "Hawaiian Shorts", value: "shorts" },
  ];
<>
<Form
  onSubmit={onSubmit}
  render={({ handleSubmit, pristine, invalid, values }) => (
    <form onSubmit={handleSubmit} className="p-5">
      {products &&
        products.map((product, idx) => (
          <div className="custom-control custom-checkbox" key={idx}>
            <Field
              name="state"
              component="input"
              type="checkbox"
              value={product.value}
            />
            <label
              className="custom-control-label"
              htmlFor={`customCheck1-${product.value}`}
            >
              {product.label}
            </label>
          </div>
        ))}
      <button type="submit" disabled={pristine || invalid}>
        Submit
      </button>
      <pre>{JSON.stringify(values, 0, 2)}</pre>
    </form>
  )}
/>
</>

如果我选择复选框,选中的值会显示像 [tshirt,cup] 这样的值数组,但我需要显示像 [ { label: "T Shirt", value: "tshirt" }, { label 这样的对象数组:“白杯”,值:“杯”}] 我尝试了很多方法,但我没有任何运气。请帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

values 将始终是由 Field 标记的“value”属性组成的数组。 如果您想要产品数组中的对象,您可以执行以下操作

console.log(values.map(val => products.find(p => p.value === val)))

或者先通过reduce创建一个对象然后使用它。

const obj =products.reduce((map,p)=>{
map[value]=p
return map
},{})

console.log(values.map(v => productMap[v]))

答案 1 :(得分:0)

为您的输入添加一个 onchange 方法。方法必须取产品的价值。

const [selectedProducts, setSelectedProducts] = useState([]);
    const handleChange = (value) =>{
        const itemToAdd = products.find(product => product.value === value);
        const index = selectedProducts.findIndex(item => item.value === value);

        if (index === -1){
            setSelectedProducts([...selectedProducts, products[index]])
        }else {
            const data = [...selectedProducts];
            data.splice(index, 1);
            setSelectedProducts(data);
        }
    }

对 jsx 的一些更改

<Field
   onChange = {handleChange}
   name="state"
   component="input"
   type="checkbox"
   value={product.value}
   checked = {selectedProducts.findIndex(item => item.value === value)!== -1}
/>
相关问题