【问题标题】:In my React component TextField, why is the value always staying the same even when I change it?在我的 React 组件 TextField 中,为什么即使我更改了值也始终保持不变?
【发布时间】:2020-09-02 20:18:16
【问题描述】:

我正在尝试使用 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 中?

【问题讨论】:

    标签: reactjs material-ui state textfield


    【解决方案1】:

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

    onChange={values.recipientDisplayName}

    【讨论】:

      猜你喜欢
      • 2012-11-02
      • 2011-07-07
      • 2023-03-20
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2021-06-17
      • 2021-03-11
      • 1970-01-01
      相关资源
      最近更新 更多