0

我尝试在 React 中制作一个自定义复选框。我能够做到,但一旦我检查了它,我将无法恢复它。我从 JSON 数据中检查和未检查的值。

组件代码

<td>
  <div class="custom-control custom-checkbox">
    <input
      type="checkbox"
      checked={venue.block}
      class="custom-control-
      input"
      id={'block-venue-' + venue.id}
      name={'block-venue-' + venue.id}
    />
    <label class="custom-control-label" for={'block-venue-' + venue.id}></label>
  </div>
</td>

JSON 对象示例

[
  {
    "id":"one",
    "photo":"/img/venue.jpg",
    "name":"One",
    "address":"saket, new delhi",
    "manager":"pranay kumar",
    "email":"pranay.kumar@hello.com",
    "phone":"00900090",
    "block":true
  },
]

4

1 回答 1

0

请检查这个例子:

import React, {useState} from "react";

export default function CustomCheckboxExample() {
    let data = [
        {
            "id": "one",
            "photo": "/img/venue.jpg",
            "name": "One",
            "address": "saket, new delhi",
            "manager": "pranay kumar",
            "email": "pranay.kumar@hello.com",
            "phone": "00900090",
            "block": true
        },
        {
            "id": "two",
            "photo": "/img/two.jpg",
            "name": "Two",
            "address": "saket, new delhi",
            "manager": "John",
            "email": "john@hello.com",
            "phone": "234234234",
            "block": false
        },
    ];

    function changeHandler(venueId, value) {
        // update value in data using venueId
    }
    return (
        <div>
            <CustomCheckbox venue={data[0]} changedValue={changeHandler}/>
        </div>
    );
}

function CustomCheckbox({venue, changedValue}) {
    const [value, setValue] = useState(venue.block);

    function changeHandler(event) {
        setValue(event.target.checked);
        changedValue(venue.id, event.target.checked);
    }
    return (
        <div className="custom-control custom-checkbox">
            <input
                type="checkbox"
                checked={value}
                onChange={changeHandler}
                className="custom-control-input"
                id={'block-venue-' + venue.id}
                name={'block-venue-' + venue.id}
            />
            <label className="custom-control-label" htmlFor={'block-venue-' + venue.id}>{venue.name}</label>
        </div>
    );
}
于 2020-05-18T20:01:47.403 回答