【问题标题】:How change the format of checkbox in react final form如何在反应最终形式中更改复选框的格式
【发布时间】:2021-06-08 18:01:23
【问题描述】:

我通过 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 :“白杯”,价值:“杯子”}] 我尝试了很多方法,但我没有任何运气。请帮我解决这个问题

【问题讨论】:

    标签: javascript reactjs react-final-form


    【解决方案1】:

    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]))
    

    【讨论】:

    • 需要更新 react 最终形式的状态
    【解决方案2】:

    为您的输入添加一个 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}
    />
    

    【讨论】:

    • 这可以工作,但它不应该更新反应最终形式的状态
    • 为什么不呢?我觉得它应该更新那个状态
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2020-09-21
    • 2019-11-09
    相关资源
    最近更新 更多