如何编辑 TextField 值,该值已预先定义

How to edit the TextField value, with the value is already pre defined

我有一个表格,其中包含来自某个国家/地区的一些数据。默认情况下,数据是只读的,如果用户想要更改值,请单击编辑按钮。

问题是我无法编辑 TextInput 中的值,默认情况下,值 value 已经预先定义。我尝试通过 onChange() 编辑值,但它不起作用。

我输入的所有内容都没有出现在输入字段中。

这是我的代码,我放在 CodeSandBox 中:https://codesandbox.io/s/polished-water-muq69?file=/src/App.js

我正在使用 react-materialTextField

有人可以帮我更新那个值吗?提前谢谢你。

我不是 React 专家,但 React 组件似乎覆盖了所有正在键入的更改。您可以在开发控制台上看到它,只需删除 value="brazil" 并尝试输入内容,value="brazil" 将弹出回到输入标签。 我可以建议用占位符替换值。这样用户仍然可以看到旧值,并且能够输入新值。

使用状态 属性 作为值

const [countryName, setCountryName] = useState("");

<TextField
className={classes.field}
disabled={disabledField}
label="Name"

value={countryName}

onChange={event => {
  setCountryName(event.target.value);
}}
variant="outlined"
InputLabelProps={{
  shrink: true
}}
/>

并在 useState("") 中定义初始值或预定义值。

问题在这里:

value={item.data.Country[0].name}

您在 value 属性中设置的任何内容都将保留在其中。因此,不要在此处传递 API 响应,而是在其中传递一个状态值,并根据输入值的变化更新该状态(2 种方式数据绑定)。它将解决问题。

您必须进行的更改:

const [countryName, setCountryName] = useState("");

onChange={event => {
  setCountryName(event.target.value);  // This will update the state
}}
value={countryName}  // updated state value is used here

正如其他人所说,问题是您需要 onChangevalue 在状态中指向相同的 value/variable。

更进一步,我将清除状态中的所有这些变量并仅使用一种方法来更改属性(例如,如果您有很多字段并且代码足够长)

  const changeField = (name, value) => {
    let newCountryInfo = [...countryInfo];
    newCountryInfo[0].data.Country[0][name] = value;
    setCountry(newCountryInfo);
  };

并在每个 TextField 中根据字段添加如下内容

  onChange={event => {
    changeField("name", event.target.value);
  }}

勾选this codesandbox link