使用复选框反应 TypeScript MultiSelector

React TypeScript MultiSelector using checkbox

我正在尝试使用 React typescript props 创建一个搜索表单 event.I 已经完成了一半,但现在卡在了一个复选框 multiSelector 上,我不知道如何实现 it.i 已经用谷歌搜索了很多但在 return 中一无所获。 这是我的代码。

我正在使用常见的打字稿道具事件 onChange 来设置我搜索中的所有值 Api 对象。

任何人都可以用代码或文档帮助我如何实现 React Typescript props 事件的 multiSelector 复选框。

1.here是我搜索的结构=>

enter code here

let columns = useMemo(
    () => [
        {
            Header: "Name", accessor: "username",
            Cell: (props: any) => {
                if (authoritiesList.includes("USR-U")) {
                    let path = "/users/" + props.value;
                    return createClickableLink(path, props.value);
                } else {
                    return <>
                        <span>{props.row.original.username}</span>
                    </>
                }
            },
            FilterOptions: {
                FilterInput:
                    <input type="text" placeholder="Username..." />,
                overrideFilterLabel: "Username",
                overrideFilterAccessor: "username"

            }
        },


        {
            Header: "Role(s)", accessor: "roles", disableSortBy: true,
            Cell: (props: any) => {
                return <>
                    {props.row.original.roles.map((role: any) => {
                        return (
                            <div>
                                <span>{role}</span><br/>
                            </div>)
                    })}
                </>
            },
            FilterOptions: {
                FilterSelect:
                         roleData.items.map((curRole:any)=>{
                            return (
                                <input type="checkbox value= 
                                {curRole.name} /> 
               
                            )
                        })} ,
                overrideFilterLabel: "Roles",
                overrideFilterAccessor: "roles"
            }
        },

    
        },
    ], [customerData,roleData]
)



enter code here

const 选择器 = (state: any) => state.users;

return (
    <div className="m-0 p-0 ">
        <section id="content-wrapper">

            <div className="row">
                <div className="col-lg-12 ml-auto">
                    <Breadcrumb crumbs={crumbs}/>
                    <div className="table_data mt-2">

                        {createSearchButton()}
                        {authoritiesList.includes("USR-C") && createAddButton("/users/create", "Add User")}

                        <DataTable columns={columns}
                                   fetchAction={userActions.getAllData as Dispatch<Action>}
                                   exportAction={userActions.exportData  as Dispatch<Action>}
                                   selector={selector}/>
                    </div>
                </div>
            </div>
        </section>
    </div>
);

}

我想处理此表单的多选复选框事件 打字稿。所有表单输入标签目前都在工作,但多选复选框无法将输出输出到查询对象。

这是我的打字稿代码。

for (let column of tableColumns) {
    if (!column.FilterOptions) {
        column.FilterOptions = {};
    }

    if (column.FilterOptions?.FilterSelect) {
        column.FilterOptions.FilterSelect.props.onKeyPress = (event: KeyboardEvent) => {
            event.key === 'Enter' && setApplyFilter(true);
        }

        column.FilterOptions.FilterSelect.props.onChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
            updateFilterQuerySelect(column, filterQuery, setFilterQuery, event);
        }
    }

    if (column.FilterOptions?.FilterInput) {
        column.FilterOptions.FilterInput.props.onKeyPress = (event: KeyboardEvent) => {
            event.key === 'Enter' && setApplyFilter(true);
        }

        column.FilterOptions.FilterInput.props.onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
            updateFilterQuery(column, filterQuery, setFilterQuery, event);
        }
    }
}

这里是函数 updateFilterQuery

const updateFilterQuery =(列:DataTableColumn,filterQuery:任何,setFilterQuery:函数,事件:React.ChangeEvent)=> {

let tempQuery: any = {...filterQuery};

let key: string = column.FilterOptions?.overrideFilterAccessor || column.accessor;
let value: any = event.target.value;

if (event.target.value == "on" && event.target.checked != undefined) {
    value = event.target.checked;
}

if (event.target.value == undefined) {
    delete tempQuery[key];
} else {
    key === 'phone' ? tempQuery[key] = getUnformattedPhoneNumber(value)
        :
        tempQuery[key] = value;
}

setFilterQuery(tempQuery);

}

这是一个搜索表单,与其他表单类似,它的工作方式与其他表单相同,而且此表单中唯一缺少的部分是现在无法使用的多选器。

您必须将选择状态分离到自定义挂钩中。状态是所选项目的数组。

CodeSandbox

hooks.ts

import React, { useState } from "react";

export const useMultiselect = (initialValue: string[]) => {
  const [selected, setSelected] = useState<string[]>(initialValue);

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    const index = selected.indexOf(value);
    if (index > -1) {
      setSelected([...selected.slice(0, index), ...selected.slice(index + 1)]);
    } else {
      setSelected([...selected, ...[value]]);
    }
  };

  const isSelected = (value: string) => {
    return selected.includes(value);
  };

  return { selected, isSelected, onChange };
};

App.tsx

import { useMultiselect } from "./hooks";

const data = ["Apple", "Orange", "Banana", "Pear", "Peach"];

export default function App() {
  const { selected, isSelected, onChange } = useMultiselect([]);
  return (
    <div>
      <div>Select your favorite fruites!</div>
      <ul style={{ listStyleType: "none" }}>
        {data.map((value) => (
          <li key={value}>
            <input
              id={value}
              type="checkbox"
              value={value}
              checked={isSelected(value)}
              onChange={onChange}
            />
            <label htmlFor={value}>{value}</label>
          </li>
        ))}
      </ul>
      <div>Selected: {selected.join()}</div>
    </div>
  );
}