首页 > 解决方案 > 在我的 React 组件 TextField 中,为什么即使我更改了值也始终保持不变?

问题描述

我正在尝试使用 material-ui 为我的 React 表单设计一个表单控件(TextField)。我想要一个 TextField 来表示传递给我的组件的对象“任务”的字段。我有

const MissionEditView = ({ mission, toListView }) => {
  ...

  const { handleChange, values } = useForm(mission);
  const recipientDisplayName = _.get(mission, "recipientDisplayName");

  const props = { classes, mission };

  function changeFormValue(name, value) {
    handleChange({ target: { name, value } });
  }

  function handleChangeRecipientDisplayName(e) {
    e.preventDefault();
    console.log("value:" + e.target.value);
    changeFormValue("recipientDisplayName", e.target.value);
  }
...
                    <Grid item>
                    <TextField
                      className={`${classes.rootInput} ${classes.input}`}
                      id="recipientDisplayName"
                      value={recipientDisplayName}
                      placeholder="Recipient"
                      variant="outlined"
                      disabled={false}
                      onChange={handleChangeRecipientDisplayName}
                      fullWidth
                    />

问题是,每当我尝试编辑文本字段组件时,都不会进行更新。我可以在 console.log 中看到正确输入的值,但 TextField 值仍然是加载组件时的值。如何调整内容以使我的更新反映在我的 TextField 中?

标签: reactjsmaterial-uistatetextfield

解决方案


您正在将valueTextField 的属性设置为通过mission对象传入的初始值。所以它总是被设置为初始值。您需要从解构values对象中获取值

onChange={values.recipientDisplayName}


推荐阅读