首页 > 解决方案 > 关闭模式后屏幕上的多选文本输入

问题描述

我有一个模态,关闭模态后,我想在屏幕上显示在模态上选择的选项。

我的代码在这里:https ://codesandbox.io/s/react-select-xdpj7?file=/src/CreatableInputOnly.tsx

在下面的这个片段中,我将调用处理模式上文本的部分CreatableInputOnly。处理下拉列表的部分在ReactSelect通话中:

<Fragment>
      <Button onClick={handleClickOpen}>ModalButton</Button>
      <div>Selected options on the modal were: </div>
      <Dialog
        maxWidth={"sm"}
        fullWidth={true}
        open={open}
        onClose={handleClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
        classes={{
          paperFullWidth: classes.paperFullWidth
        }}
      >
        <DialogTitle id="alert-dialog-title">Dialog</DialogTitle>
        <DialogContent
          classes={{
            root: classes.dialogContentRoot
          }}
        >
          <Grid container spacing={2}>
            <Grid item xs={6}>
              <FormControl style={{ width: "100%" }}>
                <ReactSelect isMulti={true} options={country} />
              </FormControl>
            </Grid>
          </Grid>
          <Grid container spacing={2}>
            <CreatableInputOnly />
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} variant="contained">
            Close
          </Button>
        </DialogActions>
      </Dialog>
    </Fragment>

标签: reactjsmodal-dialogreact-select

解决方案


您可以在 中创建状态变量ModalTest.tsx并将 setter 函数传递给选择组件reactMaterialSelect.tsx

const [selectedValues, setSelectedValues] = React.useState([]);

然后,您可以更新代码,这将显示选定的选项。它只是一个打印label每个索引项的简单地图功能。

<div>
    Selected options on the modal were:{" "}
    {selectedValues?.length
      ? selectedValues.map((item, idx) =>
          idx !== 0 ? `, ${item.label}` : item.label
        )
      : ""}
</div>

更新组件部分以发送状态设置器值的附加道具。

<ReactSelect
   handleSelectValues={setSelectedValues}
   isMulti={true}
   options={country}
 />

reactMaterialSelect.tsx中,更改函数被更新以更改父变量中的状态。

function handleChangeSingle(value) {
  setSingle(value);
  handleSelectValues([value]);
}

function handleChangeMulti(value) {
  setMulti(value);
  handleSelectValues(value);
}

为了管理createdInputs,添加了一个新的状态变量。

const [createAbleInputs, setCreateAbleInputs] = React.useState([]);

将两种状态的结果结合起来的变量。

const combinedArray =
createAbleInputs === null
  ? [...selectedValues]
  : [...selectedValues, ...createAbleInputs];

然后createableInputsOnly根据组件的变化更新组件以改变模态中的状态。

更新了沙盒链接。


推荐阅读