reactjs - 关闭模式后屏幕上的多选文本输入
问题描述
我有一个模态,关闭模态后,我想在屏幕上显示在模态上选择的选项。
我的代码在这里: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>
解决方案
您可以在 中创建状态变量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
根据组件的变化更新组件以改变模态中的状态。
推荐阅读
- sql - SQL Server:将列转换为另一个并将其值附加到单独的列
- java - Clojure 的正则表达式解析/编译有多聪明?
- php - Magento2:如何以编程方式添加具有多个属性的可配置产品?
- firebase - 如何使搜索不区分大小写
- c# - MVC 将行拆分为列或组
- flutter - 我需要在 Flutter 中发送带有调度的通知
- flutter - widget.routeName 必须是一个以正斜杠 (/) 开头的字符串
- javascript - JavaScript - 为什么我的 API 调用变量返回未定义?
- asp.net-core - 脚本评分功能不得产生负分/查询失败/阶段查询弹性搜索的所有分片失败
- java - 线程“main”java.lang.Error 中的异常:未解决的编译问题:在scanner.scan.main(scan.java:8)