reactjs - React 将 MUI TextField 值设置为其初始状态
问题描述
我有一个Description
组件。我删掉了一些代码以使其可读(与在Accordion
- 中显示一些附加图标相关的部分无关紧要)。
const Description = (props: DescriptionProps) => {
const { editable, title, content, rows } = props;
const [descriptionContent, setDescriptionContent] = useState(content);
const [expanded, setExpanded] = useState(true);
const [editMode, setEditMode] = useState(false);
const [descriptionChanged, setDescriptionChanged] = useState(false);
const resetDescription = () => {
setDescriptionContent(content);
setDescriptionChanged(false);
};
return (
<Accordion expanded={expanded} onChange={() => setExpanded(!expanded)}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography style={{ fontWeight: "bold", marginRight: 20 }}>
{title}
</Typography>
</AccordionSummary>
<AccordionDetails>
<TextField
multiline
variant="outlined"
fullWidth
defaultValue={descriptionContent}
rows={rows}
onFocus={editable ? () => setEditMode(true) : undefined}
onBlur={editable ? () => setEditMode(false) : undefined}
onChange={() => setDescriptionChanged(true)}
/>
</AccordionDetails>
{descriptionChanged ? (
<div className="description-edit-actions">
<IconButton>
<SaveIcon />
</IconButton>
<IconButton onClick={() => resetDescription()}>
<ClearIcon />
</IconButton>
</div>
) : null}
</Accordion>
);
};
它的行为如下:
- 它是一个Accordion - 基本上是一个
<spoiler>
-like 元素,因此用户可以展开它或隐藏它的内容 - 当它没有展开时,它的“标题”包含描述预览
- 当它展开时,会出现一个TextField
- 当用户聚焦文本字段时,顶部会出现一个编辑图标
现在我添加了这个:
- 当用户更改 texfield 的值时 - 底部 div 出现,带有保存和取消图标
- 保存图标将调用 API 以部分更新某些模型 - 做
- 取消图标调用
resetDescription()
->它重置状态setDescriptionChanged
(因此带有图标的div不会出现)并将descriptionContent
变量设置为其原始值-传入道具的那个
首次呈现文本字段时,它已经包含通过defaultValue
. 问题是,当我编辑描述并按下取消按钮时:带有图标的 div 当然会消失,但我对文本字段所做的更改仍然存在。
有没有办法做到这一点,当我单击取消按钮时 - 文本字段返回其初始值(传入道具的那个)?
做这样的事情:
onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
setDescriptionContent(event.target.value);
setDescriptionChanged(true);
}}
并传递descriptionContent
as 文本字段的value=
道具有效,但这确实会触发额外的重新渲染(在每次更改时,这意味着我在文本字段中添加或减去的每个字符)我想知道这是否不是一个坏习惯 - 至少从绩效视角。
解决方案
推荐阅读
- ios - ios ionic 3中本地通知上的文件插件无法播放声音
- javascript - 事务中的 Firestore 数据争用
- ruby-on-rails - 如何在运行脚本中复制 rails 控制台输出样式?
- powershell - 缺少语句块
- java - 在没有服务器或计算机的 android 上运行 Appium 或 Selenium
- javascript - JavaScript 错误属性在一个实例和它的原型中是不同的——怎么会这样?
- apache-iotdb - 成功插入后 Apache IoTDB 返回空结果(版本 0.12.0)
- c++ - 在 GDB 中,在非调试二进制文件中的命名空间或类中调用 C++ 函数的正确方法是什么?
- java - 无法在 Springboot 上运行 java 代码示例
- javascript - 对带有可选链接的元素进行空检查