在 React 中使用一个可重用的模态组件来处理不同的输入配置是个好主意吗? (我正在使用MUI模态组件)

问题描述 投票:0回答:1

我正在开发一个 React 应用程序,我需要在应用程序的各个部分显示具有不同输入字段配置(例如,文本输入、自动完成输入、自定义输入)的模式。我正在考虑创建一个可重用的模态组件来处理这些不同的输入配置。

这个想法是有一个 CustomModal 组件,它接受输入属性作为输入字段对象的数组。每个输入字段对象都具有名称、标签、值、类型、选项(用于自动完成输入)以及特定于该输入类型的任何其他属性等属性。

然后,CustomModal 组件将根据 type 属性呈现适当的输入字段,从而允许我对不同的输入配置使用相同的组件。

以下是 CustomModal 组件的示例:

import React from 'react'; import { Modal, Box, Button } from '@mui/material'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autocomplete'; const CustomModal = ({ open, onClose, onSubmit, title, inputs, submitButtonText, }) => { const handleSubmit = () => { const inputValues = inputs.map((input) => ({ name: input.name, value: input.value, })); onSubmit(inputValues); onClose(); }; const renderInput = (input) => { switch (input.type) { case 'text': return ( <TextField key={input.name} name={input.name} label={input.label} value={input.value} onChange={input.onChange} {...input.props} /> ); case 'autocomplete': return ( <Autocomplete key={input.name} options={input.options} renderInput={(params) => ( <TextField {...params} name={input.name} label={input.label} value={input.value} onChange={input.onChange} {...input.props} /> )} /> ); default: return null; } }; return ( <Modal open={open} onClose={onClose}> <Box> <h2>{title}</h2> {inputs.map(renderInput)} <Button variant="contained" onClick={handleSubmit}> {submitButtonText} </Button> </Box> </Modal> ); };
导出默认的CustomModal;

虽然这种方法似乎在整个应用程序中提供了代码可重用性和一致的 UI,但我担心潜在的问题,例如,随着输入字段类型和配置数量的增加,模式组件可能会变得更加复杂且难以维护。

在 React 中使用一个可重用的模式组件来处理不同的输入配置是一个好主意吗?如果没有,什么是更好的方法

reactjs material-ui modal-dialog reusability code-organization
1个回答
0
投票
我同意这样的担忧,随着配置的增加,代码会变得更加复杂,文件也会增长很多。另一个问题是,拥有一个接受配置的模式意味着使用该模式的所有组件都将依赖于它,因此根据每个屏幕的要求,它可能会变得混乱。

我会做一个 CustomModal 以确保整个应用程序中的模态行为相同,但是,我会将模态的内容作为 child 属性传递,以便每个组件处理自己的逻辑。

您的 CustomModal 可以实现其余功能,例如显示可以作为道具的页眉、页脚、按钮等。这将确保您在整个应用程序中具有相同的模式功能和外观。

© www.soinside.com 2019 - 2024. All rights reserved.