首页 > 解决方案 > 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>
  );
};

它的行为如下:

现在我添加了这个:

首次呈现文本字段时,它已经包含通过defaultValue. 问题是,当我编辑描述并按下取消按钮时:带有图标的 div 当然会消失,但我对文本字段所做的更改仍然存在。

有没有办法做到这一点,当我单击取消按钮时 - 文本字段返回其初始值(传入道具的那个)?

做这样的事情:

onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
    setDescriptionContent(event.target.value);
    setDescriptionChanged(true);
}}

并传递descriptionContentas 文本字段的value=道具有效,但这确实会触发额外的重新渲染(在每次更改时,这意味着我在文本字段中添加或减去的每个字符)我想知道这是否不是一个坏习惯 - 至少从绩效视角。

标签: reactjsmaterial-ui

解决方案


推荐阅读