材质 UI 自动完成 - 使用 Redux 调度取消选中 renderOption 中的复选框 [英] Material UI Autocomplete - unchecking checkboxes in renderOption using Redux dispatch

查看:39
本文介绍了材质 UI 自动完成 - 使用 Redux 调度取消选中 renderOption 中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Autocomplete 的 renderOptions 道具中呈现了一个复选框.
我可以获取使用 onChange function(event: object, value: T | T[], reason: string) => 选择的选项列表void 从这里开始, value 参数会给我选择的选项数组,我可以将它们存储在我的减速器中.
但是如何使用 Redux dispatch 取消选中此自动完成之外的某些选项

I have a checkbox rendered in renderOptions prop of Autocomplete.
I can get the list of options selected using onChange function(event: object, value: T | T[], reason: string) => void from here the value parameter will give me the array of options selected and I can store them in my reducer.
But how can I uncheck some options from outside this Autocomplete using Redux dispatch

optionsArray = [{id: 1, title: "Abc"}
                {id: 2, title: "xyz"}
                {id: 3, title: "pqr"}]

       <Autocomplete
          multiple
          options={optionsArray}
          getOptionLabel={(option) => option.title}
          renderOption={(option, {selected}) => (
             <Box>
                <Checkbox
                  checked={selected}
                />
                {option.title}
              </Box>
          )}
          onChange={(event, options) => getSelectedOptions(options)}
          getOptionSelected={(option, value) => option.id === value.id}
          renderInput={(params) => (
            <TextField
              {...params}
              variant="outlined"
              placeholder="Select"
            />
          )}
        />

推荐答案

此代码有效:

import React, { useReducer } from "react";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import CheckBoxOutlineBlankIcon from "@material-ui/icons/CheckBoxOutlineBlank";
import CheckBoxIcon from "@material-ui/icons/CheckBox";
import { Chip } from "@material-ui/core";

const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;

const options = [
  ...
];

const initialState = { selectedOptions: [] };

function reducer(state, action) {
  switch (action.type) {
    case "SET_SELECTED_OPTIONS":
      return { selectedOptions: action.payload.options };

    case "REMOVE_OPTION":
      return {
        selectedOptions: state.selectedOptions.filter(
          (option) => option.id !== action.payload.id
        )
      };
    default:
      throw new Error();
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);

  const handleChange = (event, values) => {
    dispatch({ type: "SET_SELECTED_OPTIONS", payload: { options: values } });
  };

  const removeOption = (id) => {
    dispatch({ type: "REMOVE_OPTION", payload: { id: id } });
  };

  return (
    <>
      <Autocomplete
        multiple
        options={options}
        disableCloseOnSelect
        getOptionLabel={(option) => option.title}
        value={state.selectedOptions}
        renderTags={(values) =>
          values.map((value) => (
            <Chip
              key={value.id}
              label={value.title}
              onDelete={() => {
                removeOption(value.id);
              }}
            />
          ))
        }
        getOptionSelected={(option, value) => option.id === value.id}
        renderOption={(option, { selected }) => (
          <React.Fragment>
            <Checkbox
              icon={icon}
              checkedIcon={checkedIcon}
              style={{ marginRight: 8 }}
              checked={selected}
            />
            {option.title}
          </React.Fragment>
        )}
        style={{ width: 500 }}
        onChange={handleChange}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="outlined"
            label="Checkboxes"
            placeholder="Favorites"
          />
        )}
      />
      <Button
        variant="contained"
        color="secondary"
        onClick={() =>
          dispatch({
            type: "SET_SELECTED_OPTIONS",
            payload: {
              options: [
                {
                  id: 30,
                  title: "Once Upon a Time in the West",
                  year: 1968,
                  checked: false
                }
              ]
            }
          })
        }
      >
        Simulate changes from outside
      </Button>
      <pre>{JSON.stringify(state, null, 2)}</pre>
    </>
  );
}


如您所见,我使用 react useReducer 函数模拟了您的 redux 存储.您只需存储选定的对象,当它们被删除时,您也只需将它们删除.为此,您必须渲染标签才能访问 onDelete 函数.现在您可以从外部控制所选项目.

I simulated your redux store with the react useReducer function as you can see. You just store the selected objects and when they are removed you just remove them too. For this you have to render the tag to have access to the onDelete function. Now you can control the selected items from outside.

这篇关于材质 UI 自动完成 - 使用 Redux 调度取消选中 renderOption 中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆