【问题标题】:how can I put elements of an array in a checkbox?如何将数组的元素放在复选框中?
【发布时间】:2021-02-15 16:40:14
【问题描述】:

我正在使用 react hooks 并且在后端调用后有一个动态填充的值数组。然后我怎样才能在复选框中插入这些值(我不知道先验)? 我从另一个组件中获得了一些属性。 这些属性会根据表中的选择而改变。 当我打开“可用角色列表”时,我希望能够根据复选框上的选择添加/删除这些属性

const UsersList = (props) => {
  const { loadedRoles } = props;
  const [checked, setChecked] = useState([]);

  const selectHandler = (Event, selected) => {
    loadedRoles(selected.roles);
  };

  const handleChange = (Event) => {
    setChecked({ ...props.roles, [Event.target.name]: Event.target.checked });
  };
  return (
    <div>
      <MaterialTable
        title=" Users List"
        data={props.users}
        columns={[
          { title: "User Id", field: "id" },
          { title: "Active", field: "active" },
          { title: "System", field: "system" },
          { title: "Roles", field: "roles" },
        ]}
        options={{
          cellStyle: {
            width: 100,
            minWidth: 100,
            height: 1,
          },
          headerStyle: {
            width: 100,
            minWidth: 100,
          },
        }}
        onRowClick={selectHandler}
      />
      <Card>Current Role: {props.current}</Card>
      <Card>
        <label>Available Roles: {props.roles}</label>
        <Checkbox name={props.roles} onChange={handleChange} />
      </Card>
    </div>

【问题讨论】:

  • 向我们展示您的代码,以便我们提供帮助...
  • 到目前为止您尝试过什么? “在复选框中插入值”是什么意思?
  • 对不起,我只是在使用反应,所以我不知道我是否是认真的...我编辑问题

标签: reactjs checkbox react-hooks qcheckbox


【解决方案1】:

我可以假设您从后端收到一个对象数组,其中包含复选框的标签、键和值?

[
  { label: 'Checkbox #1', key: 'checkbox1', checked: true },
  { label: 'Checkbox #2', key: 'checkbox2', checked: false },
  { label: 'Checkbox #3', key: 'checkbox3', checked: true },
]

您可以在 useEffect 中调用 API,通过 useState 将结果存储在本地状态中,然后遍历渲染中的值:

const [checkboxes, setCheckboxes] = useState(null)

useEffect(() => {
  fetch('/your/api')
    .then(res => res.json())
    .then(checkboxes => setCheckboxes(checkboxes))
}, [])

return (
  <ul>
    {checkboxes === null
      ? <li>Loading...</li>
      : checkboxes.map(checkbox => (
          <li key={checkbox.key}>
            <label>
              <input type="checkbox" name={key} defaultChecked={checkbox.checked} />
              {checkbox.label}
            </label>
          </li>
        ))
    }
  </ul>
)

此处的复选框不受控制 (defaultChecked)。要改用受控复选框,您需要创建另一个本地状态并根据后端返回的值对其进行初始化,并改用 checkedonChange 属性。

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多