首页 > 解决方案 > ReactJS:基于后端数据的 CSS3 自定义 CheckBox 值

问题描述

这是自定义复选框 reactJS 组件,

import * as React from "react";
import styled from "../../styled-components";
import { Field } from "react-final-form";

interface Props<FieldValue = string, T extends HTMLElement = HTMLElement> {
  label: string;
  name: string;
  value?: FieldValue;
}

const Wrapper = styled.label`
  display: flex;
  ...

  input {
    position: absolute;
    ...
  }

  input[type="checkbox"]:checked + span:after {
    content: "";
    display: block;
    ...
  }

  input[type="checkbox"]:focus + span {
    ...
  }
`;

const Tickmark = styled.span`
  ...
`;

function Checkbox<FieldValue = string>({
  label,
  name,
  value
}: Props<FieldValue>) {
  return (
    <Wrapper>
      <Field<FieldValue>
        name={name}
        value={value}
        component="input"
        type="checkbox"
      />
      <Tickmark />
      {label}
    </Wrapper>
  );
}

export default Checkbox;

多个复选框由另一个反应组件中的以下给定代码片段呈现。

            data.records.map((record, i) => (
                <Checkbox
                  name="records"
                  label={record.label}
                  key={record.id}
                  value={record.id}
                />
            )) 

OnSubmit,所有复选框/值都存储在后端,然后再次访问同一页面时,应该从后端获取并需要填充(选中)。

我在 Checkbox 中添加了“选中”道具,默认情况下它选中( - 复选框)并且无法取消选中它。

如何根据来自后端的值填充/选中复选框?我想知道,应该遵循一些最佳实践来实现这一目标。

感谢您的帮助,提前。

标签: cssreactjstypescriptcheckbox

解决方案


推荐阅读